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

时间:2015-11-02 09:48:26

标签: sql postgresql

我有这样一张桌子

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数组列。有谁能够帮我 ?

2 个答案:

答案 0 :(得分:17)

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

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

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

答案 1 :(得分:1)

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

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

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

   unnest
   ------
       1
       2