如何解决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
,
您可以使用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 是因为这是最常用值的统计术语。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。