PostgreSQL获得数组中最常见的值

问题描述

我有一个表,其中的列带有数组值(在group by和array_agg函数之后)

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

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

我的猜测再次出现在不必要的问题上,但我正在尝试找到更可靠,更快速方法

查询我正在用来建立表格


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

解决方法

您可以使用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

,

您可以使用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 是因为这是最常用值的统计术语。