PostgreSql 合并多行记录
需求描述:
A表有如下数据
id |
1 |
2 |
3 |
4 |
B表有如下数据
id | name |
1 | aaa |
1 | bbb |
1 | ccc |
2 | aa |
2 | bb |
3 | c |
A表和B表通过id关联,需要查询结果如下:
id | name |
1 | aaa,bbb,ccc |
2 | aa,bb |
3 | c |
4 |
查询语句如下:
- SELECT a.id,array_to_string(array(
- SELECT b.name FROM db_xx."B" b WHERE b.id=a.id
- ), ',') as name
- from db_xx."A" a
- order by a.id