how to make array_agg() work like group_concat() from mySQL

后端 未结 1 427
名媛妹妹
名媛妹妹 2020-12-29 23:15

So I have this table:

create table test (
   id integer, 
   rank integer,
   image varchar(30)
); 

Then some values:

i         


        
相关标签:
1条回答
  • 2020-12-29 23:44

    In PostgreSQL 8.4 you cannot explicitly order array_agg but you can work around it by ordering the rows passed into to the group/aggregate with a subquery:

    SELECT id, array_to_string(array_agg(image), ',')
    FROM (SELECT * FROM test ORDER BY id, rank) x
    GROUP BY id;
    

    In PostgreSQL 9.0 aggregate expressions can have an ORDER BY clause:

    SELECT id, array_to_string(array_agg(image ORDER BY rank), ',')
    FROM test
    GROUP BY id;
    
    0 讨论(0)
提交回复
热议问题