how to collect multiple values as a single string in postgres?

瘦欲@ 提交于 2020-01-14 09:38:09

问题


I have tables :

Project table

id name
-------
1  A
2  B

Assignment table

id name project_id
-------------------
1  A1   1
2  A2   1
3  A3   2

I wish to write a query that returns each project with the name of the assignments created from it, like :

project_id  assignments
-----------------------
1            A1,A2
2            A3

Is there any way to achieve that ?


回答1:


You can join the tables and use array_agg to combine the values separated by a comma

SELECT a.id, array_agg(b.name) assignments
FROM    Project a
        INNER JOIN assignment b
          ON a.id = b.project_ID
GROUP BY a.id

SQLFiddle Demo

or by using STRING_AGG

SELECT a.id, STRING_AGG(b.name, ', ' ORDER BY b.name) assignments
FROM    Project a
        INNER JOIN assignment b
          ON a.id = b.project_ID
GROUP BY a.id

SQLFiddle Demo



来源:https://stackoverflow.com/questions/13025818/how-to-collect-multiple-values-as-a-single-string-in-postgres

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