如何在Postgres中按数组列排列结果?
问题描述:
我有这样一个表如何在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;
但你确实应该解决您的数据模型。
+0
很好的答案!不知道不知道 – Matt
答
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 --
unnest(anyarray):展开阵列,以一组行
即select unnest(ARRAY[1,2])
会给
unnest
------
1
2
该查询将作为简单如您所愿,如果模型正常化。 –
你能更具体吗? –
你有一个古典的一对多关系。这不应该用一个数组来表示,而应该用两个表来表示。 https://en.wikipedia.org/wiki/Database_normalization#Example –