Combine partially repeated lines in sql join

不问归期 提交于 2019-12-13 07:24:58

问题


I have some locality tables in a PostgreSQL database:

Table loc -- the places themselves
---------
| id |  name
|  1 | Park X
|  2 | City A
|  3 | City B

Table locdad -- the hierarchical relationship between places
------------
| id | dad | loc
|  1 |  2  |  1
|  1 |  3  |  1

This describes a National Park "X" that covers city A and city B, i.e. the park has two "fathers" in the hierarchical scheme.

When I do a joined query, I get two lines for this park:

select l.id,l.name loc,l1.name dad
from loc l
join locdad ld on ld.loc = l.id
join loc l1 on l1.id = ld.dad
where l.id=1

| id |   loc  |   dad
|  1 | Park X | City A
|  1 | Park X | City B

I would like to combine the result into:

| id |   loc  |      dad
|  1 | Park X | City A, City B

How can I do that?


回答1:


Try using array_agg function like this:

select l.id,l.name loc,array_agg(l1.name) dad
from loc l
join locdad ld on ld.loc = l.id
join loc l1 on l1.id = ld.dad
where l.id=1
GROUP BY l.id,l.name

It depends on your postgres version, but to get strings seperated by commas - for 9.0+ use:

select l.id,l.name loc,string_agg(l1.name, ', ') dad
from loc l
join locdad ld on ld.loc = l.id
join loc l1 on l1.id = ld.dad
where l.id=1
GROUP BY l.id,l.name

Or this for 8.4

select l.id,l.name loc,array_to_string(array_agg(l1.name), ', ') dad
from loc l
join locdad ld on ld.loc = l.id
join loc l1 on l1.id = ld.dad
where l.id=1
GROUP BY l.id,l.name


来源:https://stackoverflow.com/questions/35702246/combine-partially-repeated-lines-in-sql-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!