postgresql - Postgresql 数组唯一聚合
问题描述
我有一张有结构的大桌子
CREATE TABLE t (
id SERIAL primary key ,
a_list int[] not null,
b_list int[] not null,
c_list int[] not null,
d_list int[] not null,
type int not null
)
我想像这样查询a_list
, b_list
, c_list
,d_list
中的所有唯一值type
select
some_array_unique_agg_function(a_list),
some_array_unique_agg_function(b_list),
some_array_unique_agg_function(c_list),
some_array_unique_agg_function(d_list),
count(1)
where type = 30
例如,对于这个数据
+----+---------+--------+--------+---------+------+
| id | a_list | b_list | c_list | d_list | type |
+----+---------+--------+--------+---------+------+
| 1 | {1,3,4} | {2,4} | {1,1} | {2,4,5} | 30 |
| 1 | {1,2,4} | {2,4} | {4,1} | {2,4,5} | 30 |
| 1 | {1,3,5} | {2} | {} | {2,4,5} | 30 |
+----+---------+--------+--------+---------+------+
我想要下一个结果
+-------------+--------+--------+-----------+-------+
| a_list | b_list | c_list | d_list | count |
+-------------+--------+--------+-----------+-------+
| {1,2,3,4,5} | {2,4} | {1,4} | {2,4,5} | 3 |
+-------------+--------+--------+-----------+-------+
有some_array_unique_agg_function
我的目的吗?
解决方案
尝试这个
with cte as (select
unnest( a_list::text[] )::integer as a_list,
unnest( b_list::text[] )::integer as b_list,
unnest( c_list::text[] )::integer as c_list,
unnest( d_list::text[] )::integer as d_list,
(select count(type) from t) as type
from t
where type = 30
)
select array_agg(distinct a_list),array_agg(distinct b_list)
,array_agg(distinct c_list),array_agg(distinct d_list),type from cte group by type ;
结果:
"{1,2,3,4,5}";"{2,4,NULL}";"{1,4,NULL}";"{2,4,5}";3
推荐阅读
- ionic-framework - 自定义组件内的 ion-item 边框
- ruby-on-rails - 广播消息发送后不会在浏览器控制台显示,actioncable和redis开发环境
- apache-spark - Spark:Reduce() 与 Fold() 之间的区别
- javascript - 在javascript中命名一个元素
- bash - 如何将 grep 输出解析为数组并对其进行迭代
- php - 码头工人和 PHP。如何向容器发出 cURL 请求?
- spring - Spring Session - 异步调用处理
- python - 无法通过双击打开 python 脚本
- c# - 为什么 azure Function App 流式日志查看器重复日志输出?
- python - mediaItems.search 不适用于专辑 ID