Search code examples
sqlpostgresqlpostgresql-9.1string-aggregation

How to select values from many rows that has the same id to just one row and separate them with -?


i'd like to display the values of the table with the same id in just one row and separate them with - or,

 row id | base_id | auth_id
--------+---------+---------
      4 |       1 |       1
      5 |       1 |       3
      6 |       2 |       2
      7 |       2 |       6
      8 |       2 |       5

result i expect

 row id | base_id | auth_id
--------+---------+---------
      1 |       1 | 1-3
      2 |       2 | 2-6-5

Solution

  • You can use string_agg() concatenation and row_number() window analytic function :

    select row_number() over (order by base_id) as row_id, 
           base_id, string_agg(auth_id::varchar,'-' order by auth_id) as auth_id
      from tab
     group by base_id;
    

    Demo