将同一张表中的行分组为同一张表中的行

时间:2018-09-05 11:43:40

标签: sql postgresql

表A

  • group_id
  • my_id

假设我有

group_id     my_id    value
  1            a        10
  1            b        15
  2            c        20
  3            d        25

我要输出

   group_id     my_id    value    family
      1            a        10     [10, 15]
      1            b        15     [10, 15]
      2            c        20     [20]
      3            d        25     [25]

2 个答案:

答案 0 :(得分:0)

使用array_agg并加入

select t1.*,t2.family from tbl t1
  join 
    (
    select group_id,array_agg(value) as family form tbl
    group by group_id
    ) as t2 t1.group_id=t2.group_id

答案 1 :(得分:0)

您可以使用相关的标量子查询:

select group_id, 
       value, 
       array(select value from the_table t2 where t2.group_id = t1.group_id) as family
from the_table t1
order by group_id;