Joining arrays within group by clause

后端 未结 2 410
心在旅途
心在旅途 2021-01-05 11:13

We have a problem grouping arrays into a single array. We want to join the values from two columns into one single array and aggregate these arrays of multiple rows.

2条回答
  •  盖世英雄少女心
    2021-01-05 11:51

    select n, array_agg(c) as c
    from (
        select n, unnest(array[c1, c2]) as c
        from t
    ) s
    group by n
    

    Or simpler

    select
        n,
        array_agg(c1) || array_agg(c2) as c
    from t
    group by n
    

    To address the new ordering requirement:

    select n, array_agg(c order by id, o) as c
    from (
        select
            id, n,
            unnest(array[c1, c2]) as c,
            unnest(array[1, 2]) as o
        from t
    ) s
    group by n
    

提交回复
热议问题