如何找到最频繁重复的列?

时间:2020-06-04 20:15:40

标签: sql sql-server count sql-order-by sql-limit

ID  UserID LevelID
1   1       1
2   1       2
3   1       2
4   1       2
5   2       1
6   2       3
7   3       2
8   4       1
9   4       1

查询应返回:LevelID:1(3次)-不同用户(UserID)最常重复的LevelID列。

我有以下查询:

SELECT LevelID, COUNT(LevelID) AS 'Occurrence' 
FROM 
(
  SELECT DISTINCT * FROM
  (
    SELECT UserID, LevelID
    FROM SampleTable
  ) cv
) levels
GROUP BY LevelID
ORDER BY 'Occurrence'  DESC

哪个返回:

LevelID Occurence
1        3      
2        2      
3        1  

但是不允许我在底部添加LIMIT 1;来检索所选内容的第一行。查询出了什么问题?

1 个答案:

答案 0 :(得分:4)

不需要这几个嵌套级别。考虑使用聚合count(distinct ...),对结果进行排序并使用行限制子句仅保留最高记录:

select top(1) levelID, count(distinct userID) cnt
from mytable
group by levelID
order by cnt desc

如果您想允许可能的平局,则使用top (1) with ties而不是top (1)

相关问题