SQL选择分组行的最高计数

时间:2014-02-14 10:10:42

标签: sql sql-server group-by

我的桌子旁边有标签和一些代码:

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)

4 个答案:

答案 0 :(得分:2)

请尝试:

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

答案 1 :(得分:2)

我与@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 here

答案 2 :(得分:0)

使用您的查询和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

答案 3 :(得分:-1)

一些,

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