如何找到最常重复的列?
How to find the most frequently repeated column?
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
查询应该return: 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
哪个 returns:
LevelID Occurence
1 3
2 2
3 1
但它不允许我在底部添加 LIMIT 1;
来检索所选内容的第一行。查询有什么问题?
不需要这几层嵌套。考虑使用聚合,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)
。
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
查询应该return: 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
哪个 returns:
LevelID Occurence
1 3
2 2
3 1
但它不允许我在底部添加 LIMIT 1;
来检索所选内容的第一行。查询有什么问题?
不需要这几层嵌套。考虑使用聚合,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)
。