查询如下:
SELECT i_adgroup_id,i_category_id FROM adgroupcategories_br WHERE i_adgroup_id IN ( SELECT i_adgroup_id FROM adgroupusers_br WHERE i_user_id = 103713 ) GROUP BY i_adgroup_id,i_category_id;
给我这样的结果:
i_adgroup_id integer | i_category_id smallint ---------------------|----------------------- 15938 | 2 15938 | 3 15938 | 4 15942 | 1 15942 | 2
我想要的结果是这样的:
i_adgroup_id integer | i_category_id smallint[] ---------------------|----------------------- 15938 | { 2,3,4 } 15942 | { 1,2 }
如何更改原始SQL查询以给出以上结果?
你想使用
原文链接:https://www.f2er.com/postgresql/193170.htmlarray_agg
,这应该工作:
SELECT i_adgroup_id,array_agg(i_category_id) FROM adgroupcategories_br WHERE i_adgroup_id IN ( SELECT i_adgroup_id FROM adgroupusers_br WHERE i_user_id = 103713 ) GROUP BY i_adgroup_id;
请注意,i_category_id不再在GROUP BY中,因为它正在聚合。