简体   繁体   中英

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.

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. Can anybody help me ?

You can use unnest() to get a normalized view on the data, and the aggregate:

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

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

   unnest
   ------
       1
       2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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