【问题标题】:SQL select top counts for grouped rowsSQL 选择分组行的最高计数
【发布时间】:2014-02-14 10:10:41
【问题描述】:

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

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)

【问题讨论】:

    标签: sql sql-server group-by


    【解决方案1】:

    我的解决方案与 @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】:

      请尝试:

      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
      

      【讨论】:

      • 内部子查询并不是真正必要的,但仍然是一个有效的解决方案。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-01
        • 2021-09-16
        • 1970-01-01
        • 1970-01-01
        • 2014-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多