簡體   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