【问题标题】:how to collect multiple values as a single string in postgres?如何在postgres中将多个值收集为单个字符串?
【发布时间】:2012-10-23 07:53:11
【问题描述】:

我有桌子:

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

有什么方法可以实现吗?

【问题讨论】:

    标签: sql postgresql postgresql-9.1


    【解决方案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 Demo

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

    【讨论】:

    • 使用 9.1 string_agg() 可能更合适。
    猜你喜欢
    • 2022-11-28
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多