Search code examples
postgresqlrowaggregate-functions

Can rows data can be customed to columns in Postgresql


I have the follow table in PostgreSQL

foreign_key_id name
1700 Joe
1700 Mark
1700 Luke
1700 Peter
1700 James

I would like to change to

foreign_key_id name
1700 Joe;Mark;Luke;Peter,James

How to do it? I have tried crosstab but it does not seems the right way. Any help ? thanks


Solution

  • Group by with aggregation should work:

    SELECT foreign_key_id, string_agg(name, ';') FROM table_name GROUP BY foreign_key_id;