如何选择列中前5个最频繁的值

时间:2018-10-25 08:22:23

标签: mysql sql sqlite

我想使用以下数据库从数据库中选择前5张最频繁的专辑:http://www.sqlitetutorial.net/tryit/query/sqlite-inner-join/#3

使用此查询:

SELECT
  albums.title AS Album,
  artists.name AS Artist,
  COUNT(albums.title ) as TitleCount
FROM tracks
INNER JOIN albums ON albums.albumid = tracks.albumid
INNER JOIN artists ON artists.artistid = albums.artistid
GROUP BY 
  albums.albumid 
ORDER BY 
  TitleCount DESC

限制5不是一个好的解决方案,因为在我的情况下,有2张专辑有25个标题,我想要的是titleCount值排在前5位的专辑。似乎limit不需要COUNT,而是整数

预期结果:

|Album               |Artist       |TitleCount|
|Greatest Hits       |Lenny Kravitz|57        |  
|Minha Historia      |Chico Buarque|34        |
|Unplugged           |Eric Clapton |30        |
|Lost, Season 3      |Lost         |26        |
|Lost, Season 1      |Lost         |25        |
|The Office, Season 3|The Office   |25        |

ps:这可能是SQL - Most frequent value in column of joined tables的副本,但我不能将其应用于我的

3 个答案:

答案 0 :(得分:2)

MySQL和SQLite的LIMIT子句都缺少WITH TIES选项,这是您在这里需要的。因此,请改用子查询:选择曲目数量最多的五个(在极少数情况下,您实际上将GROUP BYDISTINCT-GROUP BY结合在一起以获取每张专辑{{1} }以获取五个最高的不同计数),然后选择具有相同音轨的专辑。由于这是关于聚合结果的,因此它属于DISTINCT子句:

HAVING

答案 1 :(得分:0)

使用以下代码

    SELECT
  albums.title AS Album,
  artists.name AS Artist,
  COUNT(*) as TitleCount
FROM tracks
INNER JOIN albums ON albums.albumid = tracks.albumid
INNER JOIN artists ON artists.artistid = albums.artistid
GROUP BY albums.albumid 
HAVING COUNT(*) IN
(
  SELECT DISTINCT COUNT(*)
  FROM tracks
  GROUP BY albumid
  ORDER BY count(*) DESC

)
ORDER BY TitleCount DESC LIMIT 5;

答案 2 :(得分:0)

尽管其他答案很好用,但是如果您使用的是sqlite 3.25或更高版本(或者我认为是MySQL 8),则可以使用dense_rank() window function以更简单的方式完成此操作:

WITH rankings(Album, Artist, TitleCount, ranking) AS (
  SELECT al.title, ar.name, count(al.title)
       , dense_rank() OVER (ORDER BY count(al.title) DESC)
  FROM tracks AS t
  INNER JOIN albums AS al ON al.albumid = t.albumid
  INNER JOIN artists AS ar ON ar.artistid = al.artistid
  GROUP BY al.albumid)
SELECT Album, Artist, TitleCount
FROM rankings
WHERE ranking <= 5
ORDER BY ranking;