小编典典

如何在postgres中将多个值作为单个字符串收集?

sql

我有表:

Project table

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

Assignment table

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

我希望编写一个查询,以返回每个项目以及从中创建的分配名称的查询,例如:

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

有什么办法可以实现?


阅读 220

收藏
2021-04-22

共1个答案

小编典典

您可以联接表并用于array_agg合并用逗号分隔的值

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演示

或使用 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演示

2021-04-22