Reputation: 119
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?
Upvotes: 2
Views: 79
Reputation: 26046
You can use string_agg
:
select column1, string_agg(column2, ', ')
from table_name
group by column1
You can find more info here.
Upvotes: 3