我有这样一张桌子
id SERIAL,
user_id INT,
community_id INT[],
Run Code Online (Sandbox Code Playgroud)
表格填写方式如下:
id | user_id | community_id
1 | 1 | {2, 4}
2 | 5 | {2, 5}
3 | 10 | {2, 4}
Run Code Online (Sandbox Code Playgroud)
我想获得每个社区拥有的COUNT个用户,community_id是数组cuz用户可以同时在多个社区中.
查询应该简单如下:
SELECT community_id, COUNT(user_id) FROM tbl GROUP BY community_id
Run Code Online (Sandbox Code Playgroud)
结果应该是这样的:
community_id | user_count
2 | 3
4 | 2
5 | 1
Run Code Online (Sandbox Code Playgroud)
我不知道如何GROUP BY列列.有谁能够帮我 ?
a_h*_*ame 19
您可以使用unnest()获取数据的标准化视图和聚合:
select community_id, count(*)
from (
select unnest(community_id) as community_id
from tbl
) t
group by community_id
order by community_id;
Run Code Online (Sandbox Code Playgroud)
但是你应该真正修复你的数据模型.
| 归档时间: |
|
| 查看次数: |
4336 次 |
| 最近记录: |