【问题标题】:Find most occurring value in a group查找组中出现次数最多的值
【发布时间】:2019-10-27 10:19:16
【问题描述】:

我想找到每组出现次数最多的值。

我尝试使用 top(k)(column) 但出现以下错误: 列类不在聚合函数下,也不在 GROUP BY 中。

例如: 如果我有带有列(pid,值)的表 test_date

pid, value
----------
1,a
1,b
1,a
1,c

我想要结果:

pid, value
----------
1,a

我试过SELECT pid,top(1)(value) top_value FROM test_data group by pid

I get the error: 

Column value  is not under aggregate function and not in GROUP BY

我也试过anyHeavy(),但它只适用于出现超过一半情况的值

【问题讨论】:

    标签: clickhouse


    【解决方案1】:
    SELECT pid,topK(1)(value) top_value FROM test_data group by pid
    

    【讨论】:

      【解决方案2】:

      这个查询应该可以帮助你:

          SELECT
              pid,
              /*
              Decompose the query in parts:
              1. groupArray((value, count)): convert the group of rows with the same 'pid' to the array of tuples (value, count)
              2. arrayReverseSort: make reverse sorting by 'count' ('x.2' is 'count')
              3. [1].1: take the 'value' from the first item of the sorted array
              */
              arrayReverseSort(x -> x.2, groupArray((value, count)))[1].1 AS value
          FROM
          (
              SELECT
                  pid,
                  value,
                  count() AS count
              FROM test_date
              GROUP BY
                  pid,
                  value
          )
          GROUP BY pid
          ORDER BY pid ASC
      

      【讨论】:

      • 这可行,但查询很复杂。我看到有 topK 函数,它也是一样的。
      • 我故意忽略了这个reasontopK:“这个函数不提供保证的结果。在某些情况下,可能会发生错误并且它可能会返回频繁的值不是最常见的值”。
      猜你喜欢
      • 2011-04-29
      • 2017-06-27
      • 1970-01-01
      • 2011-04-17
      • 2013-07-14
      • 2021-02-01
      • 2021-10-28
      • 2018-09-23
      • 1970-01-01
      相关资源
      最近更新 更多