我有一张桌子旁边有标签和代码:
id | label | code
1 | foo | 21
2 | foo | 33
3 | foo | 33
4 | foo | 13
5 | foo | 13
6 | foo | 33
7 | bar | 13
8 | bar | 13
9 | bar | 33
10 | smt | 33
11 | smt | 13我需要一个查询,为每个“标签”选择“代码”的最高频率。以下是我到目前为止所拥有的:
SELECT count(*) frequency, label, code
FROM myTable
GROUP BY label, code这给了我:
frequency | label | code
1 | foo | 21
3 | foo | 33
2 | foo | 13
2 | bar | 13
1 | bar | 33
1 | smt | 33
1 | smt | 13但我想要的是:
frequency | label | code
3 | foo | 33
2 | bar | 13
1 | smt | 33
1 | smt | 13如您所见,只有顶部的频率被选择为'foo‘和'bar’。由于'smt‘本身没有最大频率(都是相同的),所以所有行都包括在内。
我甚至不知道从哪里开始。有人能帮忙吗?谢谢。(顺便说一下,我正在使用mssql )
发布于 2014-02-14 10:39:37
我的类似解决方案是@TechDo,但有一个子查询
SELECT frequency,label,code FROM
(
SELECT
count(*) AS frequency
,MAX(COUNT(*)) OVER (PARTITION BY label) AS Rnk
,label
,code
FROM myTable
GROUP BY label, code
) x
WHERE frequency=Rnk
ORDER BY frequency DESCSQLFiddle 这里
发布于 2014-02-14 10:24:37
请尝试:
SELECT * FROM(
SELECT *,
MAX(frequency) OVER(PARTITION BY label) Col1
FROM(
SELECT count(*) frequency, label, code
FROM myTable
GROUP BY label, code
)x
)xx
WHERE frequency=Col1发布于 2014-02-14 10:25:41
使用查询和RANK()
SELECT frequency, label, code FROM
(
SELECT frequency, label, code, RANK() OVER(PARTITION BY code ORDER BY frequency DESC) [rank]
FROM (
SELECT count(*) frequency, label, code
FROM myTable
GROUP BY label, code
) Counts
) Ranked
WHERE [rank] = 1
ORDER BY frequency DESChttps://stackoverflow.com/questions/21776385
复制相似问题