简体   繁体   中英

SQL : query to retrieve data

I'm working on a SQL project where i have the tables Actor AlbumId TrackId InvoiceLine and Invoice and i want to retrieve the names of the actors whose tracks are the top 3 sold.

ex(from a table of 10 artists ) .

Drake (300 tracks sold )

Kendrick (233 tracks)

Cardi B (200 tracks)

I'm new to SQL and i have my diagram below . I know that i have to connect the tables of actor album track and invoice to get the 3 max(count(trackid)) from the invoiceline table to give me the names of the actors that have made the specific tracks

Thank you for your time在此处输入图片说明

Below joins the relevant tables together and uses the aggregrate COUNT function to count the number of invoice lines associated with a song.

You may want to use TOP 3 WITH TIES in case there are two artists in third place with same number of sales

SELECT  TOP 3
        ar.Name
FROM    InvoiceLine il
        JOIN Track t
            ON il.TrackId = t.TrackId 
        JOIN Album al
            ON al.AlbumId = t.AlbumId
        JOIN Artist ar
            ON ar.ArtistId = al.ArtistId
GROUP BY ar.Name
ORDER BY COUNT(t.TrackId) DESC

If you're looking for the top 3 tracks sold then this will give you the top 3 trackids. Then join this to your Track, Album and Artist tables to get the artist.

SELECT TOP 3 trackid 
FROM InvoiceLine
GROUP BY trackid
ORDER BY COUNT(trackid) DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM