简体   繁体   中英

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_category_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM