[英]SQL select top counts for grouped rows
我有一个表格,旁边有标签和一些代码:
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)
请试试:
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
我和@TechDo类似的解决方案,但有1个子查询
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 DESC
SQLFiddle 在这里
使用您的查询和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 DESC
有些,
with cte as
(SELECT count(*) frequency, label, code
FROM myTable
GROUP BY label, code
)
,cte1 as
(
Select *,ROW_NUMBER()over order(partition by label order by frequency)rn1
)
select * from cte1 where rn=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.