简体   繁体   中英

How to get column value with customize array in Postgresql?

I have a query result like below in c_order table for c_order_id colunm.

c_order_id
----------
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
....
....
....

I need a query for below result.

c_order_id
----------
1001,1002,1003,
1004,1005,1006,
1007,1008,1009,
1010,....,....

or

c_order_id
-----------
1001,1002,1003,1004,
1005,1006,1007,1008,
1009,1010,....,....

I concern with array_to_string(array_agg(c_order_id), e'\\n') where i get an array result but in per array value in per new line. Here i can't customize array value with new line.

Do two levels of aggregation:

select string_agg(col_3, '\n')
from (select string_agg(col, ',') as col_3
      from (select t.*,
                    row_number() over (order by col) - 1 as seqnum
            from t
           ) t
      group by floor(seqnum / 3)
     ) t;

Thank you Gordon Linoff. But need little correction

select string_agg(col_3, e'\n') c_order_id
from (select string_agg(c_order_id::character varying, ',') as col_3
      from (select t.c_order_id,
                    row_number() over (order by c_order_id) - 1 as seqnum
            from c_order t
           ) t
      group by floor(seqnum / 4)
     ) c_order ;

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