Search code examples
sqlpostgresqlgroup-bystring-aggregation

SQL Concatenate all values in column B that have same value in column A for all values in column A


I am running PostgreSQL 12.4. I have a relatively large table like the following where column 1 and 2 are both of character varying type:

|---------------------|------------------|
|       Column 1      |     Column 2     |
|---------------------|------------------|
|         foo         |         X        |
|---------------------|------------------|
|         foo         |         Y        |
|---------------------|------------------|
|         foo         |         Z        |
|---------------------|------------------|
|         bar         |         A        |
|---------------------|------------------|
|         bar         |         B        |
|---------------------|------------------|
|         bar         |         C        |
|---------------------|------------------|

I would like to create something like the following:

|---------------------|------------------|
|       Column 1      |     Column 2     |
|---------------------|------------------|
|         foo         |      X, Y, Z     |
|---------------------|------------------|
|         bar         |      A, B, C     |
|---------------------|------------------|

Is there an easy way to do this?


Solution

  • You can use string_agg:

    select column1, string_agg(column2, ', ')
    from table_name
    group by column1
    

    You can find more info here.