【问题标题】:Postgresql get the most common value in arraypostgresql 获取数组中最常见的值
【发布时间】:2020-08-11 13:18:56
【问题描述】:

我有一个包含数组值列的表(在 group by 和 array_agg 函数之后)

COLUMN_VALUE          | other_columns...
-----------:          | -------:
 {0.45,0.45,0.97,0.99}|        ..
 {0.45,0.45,0.85,0.99}|        ..
 {0.45,0.45,0.77,0.99}|        ..
 {0.45,0.45,0.10,0.99}|        ..

如何获得最频繁的值? (这种情况下每行 0.45)

我的猜测又是 unnest 和 groupby,但我正试图找到更强大和更快的东西。

我用来构建表格的查询


select column1, column2, column3, array_agg(column4) as prices
from tb
where some conditions
group by 1, 2, 3

【问题讨论】:

  • "在 group by 和 array_agg 函数之后" - 你为什么不使用mode() 聚合期间呢?请edit您的问题并添加您当前使用的查询
  • 我无法共享查询,因为它包含我无法共享的信息。我将尝试更好地解释我使用的内容。不确定如何使用模式,但会编辑我的问题

标签: sql postgresql aggregate-functions


【解决方案1】:

您可以使用mode() 聚合在聚合期间获得最频繁的值:

select column1, column2, column3, 
       array_agg(column4) as prices
       mode() within group (order by column4 desc) as most_frequent_price
from tb
where ...
group by 1, 2, 3

Online example

【讨论】:

  • 所以基本上我不需要使用那个array_agg(column4)。如果我们有两个频繁取最高/最小的值,有什么提示吗?
  • @ShayHa:quote from the manual如果有多个相同频率的结果,则任意选择第一个”。在这种情况下,我不知道有一种方法可以优先考虑另一个
  • 您可以通过在 column4 后添加 desc 来解决此问题,然后它将返回最高值,否则它的顺序为 asc,因此您得到最低值。组内的 mode()(按 column4 desc 排序)
  • @ShayHa:啊,我误解了你的问题。如果您有两个不同的值出现相同的次数,我以为您是在询问将一个值优先于另一个值。
【解决方案2】:

你可以使用unnest()和一些聚合逻辑:

select t.*, m.mode
from t cross join lateral
     (select el as mode
      from unnest(t.column_value) el
      group by el
      order by count(*) desc
      limit 1
     ) m;

我称它为 mode,因为这是最常见值的统计术语。

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 2011-02-08
    • 2016-06-23
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    相关资源
    最近更新 更多