[英]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.我正在处理一个 SQL 项目,其中我有表 Actor AlbumId TrackId InvoiceLine 和 Invoice,我想检索其曲目销量排名前三的演员的姓名。
ex(from a table of 10 artists ) .例如(来自 10 位艺术家的表格)。
Drake (300 tracks sold )德雷克(售出 300 首曲目)
Kendrick (233 tracks)肯德里克(233 首曲目)
Cardi B (200 tracks) Cardi B(200 首曲目)
I'm new to SQL and i have my diagram below .我是 SQL 的新手,下面有我的图表。 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
我知道我必须连接演员专辑曲目和发票的表才能从发票行表中获得 3 max(count(trackid)) 来给我制作特定曲目的演员的名字
Below joins the relevant tables together and uses the aggregrate COUNT
function to count the number of invoice lines associated with a song.下面将相关表格连接在一起,并使用聚合
COUNT
函数计算与歌曲关联的发票行数。
You may want to use TOP 3 WITH TIES in case there are two artists in third place with same number of sales您可能需要使用 TOP 3 WITH TIES,以防有两位艺术家排名第三,销售额相同
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.如果您正在寻找销量最高的 3 首曲目,那么这将为您提供前 3 名的 trackid。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.