开发者

PostgresQL SQL: Converting results to array

The query below:

    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;

Gives me results like this:

    i_adgroup_id integer | i_category_id smallint
    ---------------------|-----------------------
    15938                | 2
    15938                | 3
    15938                | 4
    15942                | 1
    15942                | 2

What I want is results like this:

    i_adgroup_id integer | i_ca开发者_Go百科tegory_id smallint[]
    ---------------------|-----------------------
    15938                | { 2, 3, 4 }
    15942                | { 1, 2 }

How can I change the original SQL query to give me the result above?


You want to use array_agg, this should work:

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;

Note that i_category_id is no longer in the GROUP BY as it is now being aggregated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜