按数组中的列聚合数据

Aggregating data by column in array

假设我有以下数据:

gp_id | p_id
------|-------
1     | 123
2     | 432
2     | 222

出于业务逻辑的目的,我必须将其转换为:

gp_id | p_ids
------|----------
1     | {123}
2     | {432,222}

我试过这样做(实际上,我知道这是错误的做法,但仍然如此):

select gp_id, array(
    select p_id from cte
    ) as p_ids
from cte

而且,不出所料,它 returns 以下内容:

gp_id | p_ids
------|--------------
1     | {123,432,222}
2     | {123,432,222}
2     | {123,432,222}

谁能帮我解决这个问题?
是的,事实上,我在一系列常见的 table 表达式中使用了它。

我想你可以使用 array_agg :

select
    gp_id, array_agg(p_id) as p_ids
from cte
group by gp_id

尝试以下查询:

select c1.gp_id, array(
    select p_id from cte c2 where c2.gp_id = c1.gp_id
    ) as p_ids
from cte c1 group by c1.gp_id;

select gp_id, group_concat(p_id) p_ids
from cte group by gp_id;