以下查询:
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查询以向我提供上述结果?
答案 0 :(得分:51)
您想使用array_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
,因为它现在正在汇总。