繁体   English   中英

如何在Postgres中按数组列对结果进行分组?

[英]How to group result by array column in Postgres?

我有这样一张桌子

id SERIAL,
user_id INT,
community_id INT[],

表格填写方式如下:

id | user_id | community_id 
1  |  1      |   {2, 4}
2  |  5      |   {2, 5} 
3  |  10     |   {2, 4}

我想获得每个社区拥有的COUNT个用户,community_id是数组cuz用户可以同时在多个社区中。

查询应该简单如下:

SELECT community_id, COUNT(user_id) FROM tbl GROUP BY community_id

结果应该是这样的:

community_id  | user_count
2             |  3
4             |  2
5             |  1

我不知道如何GROUP BY数组列。 有谁能够帮我 ?

您可以使用unnest()来获取数据的标准化视图和聚合:

select community_id, count(*)
from (
  select unnest(community_id) as community_id
  from tbl 
) t
group by community_id
order by community_id;

但是你应该真正修复你的数据模型。

select unnest(community_id) community_id
      ,count(user_id) user_count
from table_name
group by 1 --community_id = 1 and user_count = 2 (index of a column in select query)
order by 1 -- 

sqlfiddle


unfst(anyarray)将数组扩展为一组行

select unnest(ARRAY[1,2])将给出

   unnest
   ------
       1
       2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM