从表结果中计算值

时间:2012-01-22 23:28:43

标签: sql sql-server

我有一个数据表,如下所示:

     ArtistName    TrackName             TrackID

1    Pendulum      Slam                  6
2    N/A           N/A                   26
3    N/A           N/A                   26
4    N/A           N/A                   26
5    Snow Patrol   Chasing Cars          17
6    Snow Patrol   Chasing Cars          17
7    Rihanna       Love The Way You Lie  4
8    N/A           N/A                   26
9    N/A           N/A                   26
10   Kanye West    Stronger              10
11   Rihanna       Love The Way You Lie  4
12   N/A           N/A                   26
13   N/A           N/A                   26
14   Tinie Tempah  Written In The Stars  8
15   N/A           N/A                   26
16   N/A           N/A                   26
17   Nero          Crush On You          18

等...

基本上我想做的是计算每个TrackID的出现次数,并在列中显示。上一个表是根据此查询创建的,该查询结合了其他几个表:

SELECT Artist_Details.ArtistName, Track_Details.TrackName, Sales_Records.TrackID 
FROM Track_Details 
INNER JOIN Sales_Records ON Track_Details.TrackID = Sales_Records.TrackID 
JOIN Artist_Details ON Track_Details.ArtistID = Artist_Details.ArtistID;

我想要的输出格式是:

     ArtistName    TrackName             Track ID    TotalSales

1    Pendulum      Slam                  6           8
2    Tinie Tempah  Written In The Stars  8           5
3    Rihanna       Love The Way You Lie  4           2

最后,我希望值26不被计算并被忽略而不会显示在结果中,并按TotalSales排序。如果可能的话,将此图表限制为10行。

提前致谢,Mark

1 个答案:

答案 0 :(得分:1)

这看起来像是group by的扣篮:

SELECT top 10 Artist_Details.ArtistName, Track_Details.TrackName, 
      Sales_Records.TrackID, count(Sales_Records.TrackID) as TotalSales
FROM Track_Details 
INNER JOIN Sales_Records ON Track_Details.TrackID = Sales_Records.TrackID 
JOIN Artist_Details ON Track_Details.ArtistID = Artist_Details.ArtistID
WHERE Sales_Records.TrackID <> 26
GROUP BY Artist_Details.ArtistName, Track_Details.TrackName, Sales_Records.TrackID
ORDER BY count(Sales_Records.TrackID) desc