在SQL中查找计数的最大值

时间:2014-12-08 11:31:25

标签: sql sql-server select count group-by

我有一个音乐曲目数据库,我试图找到哪个类型的曲目最多。类型存储在工作表中,“跟踪”表中的每个轨道都有一个属于其所属工作的字段。

此查询正确返回类型以及它们各自拥有的轨道数:

SELECT w.genre
     , COUNT(t.name) [numTracks] 
  FROM Track t
  LEFT 
  JOIN Work w 
    ON t.workName = w.name 
  LEFT 
  JOIN AlbumContains ta
    ON ta.workName = t.workName  
 GROUP 
    BY w.genre

但我无法找到一种方法来从该结果中获取具有最高numTracks的任何类型(或多种类型)。

提前致谢!

3 个答案:

答案 0 :(得分:1)

试试这个:

<强>的MySQL

SELECT w.genre, COUNT(t.name) AS numTracks
FROM work w 
LEFT JOIN Track t ON t.workName = w.name 
GROUP BY w.genre
ORDER BY COUNT(t.name) DESC 
LIMIT 1

SQL SERVER

SELECT TOP 1 w.genre, COUNT(t.name) AS numTracks
FROM work w 
LEFT JOIN Track t ON t.workName = w.name 
GROUP BY w.genre
ORDER BY COUNT(t.name) DESC 

答案 1 :(得分:0)

select * from (SELECT Work.genre, count(Track.name) as numTracks FROM Track LEFT JOIN Work ON Track.workName=Work.name LEFT JOIN AlbumContains ON Track.workName=AlbumContains.workName GROUP BY Work.genre)alias order by aias. numTracks desc limit 1

答案 2 :(得分:0)

我认为你的问题并不完全,但不知何故类似于这个问题: SQL Select only rows with Max Value on a Column

如果你想让所有类型的曲目最多,而不仅仅是一个(据我所知,你想在你的问题中这样),那么你可能需要再次加入你的查询,或者使用像这样的子选择(MySQL的):

SELECT Work.genre, count(Track.name) as numTracks
  FROM Track
  LEFT JOIN Work ON Track.workName=Work.name
  GROUP BY Work.genre
  HAVING numTracks=
  (SELECT count(Track.name) as numTracks
    FROM Track
    LEFT JOIN Work ON Track.workName=Work.name
    GROUP BY Work.genre
    ORDER BY numTracks DESC
    LIMIT 1);

或者在MS SQL中:

SELECT Work.genre, count(Track.name) as numTracks
  FROM Track
  LEFT JOIN Work ON Track.workName=Work.name
  GROUP BY Work.genre
  HAVING count(Track.name) =
  (SELECT TOP(1) count(Track.name) as numTracks2
    FROM Track
    LEFT JOIN Work ON Track.workName=Work.name
    GROUP BY Work.genre
    ORDER BY numTracks2 DESC
  );

这看起来很尴尬,但服务器可能会优化子查询。但是,对于性能更佳的解决方案,您可以考虑使用光标。