简体   繁体   English

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

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

I have such a table 我有这样一张桌子

id SERIAL,
user_id INT,
community_id INT[],

The table filled this way: 表格填写方式如下:

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

I'd like to get COUNT of users which each community has, community_id is array cuz user can be in several community at the same time. 我想获得每个社区拥有的COUNT个用户,community_id是数组cuz用户可以同时在多个社区中。

The query should be simple as: 查询应该简单如下:

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

The result should be like this: 结果应该是这样的:

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

I do not know how to GROUP BY array column. 我不知道如何GROUP BY数组列。 Can anybody help me ? 有谁能够帮我 ?

You can use unnest() to get a normalized view on the data, and the aggregate: 您可以使用unnest()来获取数据的标准化视图和聚合:

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

But you should really fix your data model. 但是你应该真正修复你的数据模型。

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) : Expand an array to a set of rows unfst(anyarray)将数组扩展为一组行

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

   unnest
   ------
       1
       2

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

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