【问题标题】:Combine selected columns of multiple rows into one string [duplicate]将多行的选定列组合成一个字符串[重复]
【发布时间】:2019-02-21 20:32:12
【问题描述】:

假设我有下表:

table xyz

+------+--------+--------+
| id   | field1 | field2 |
+------+--------+--------+
|    3 | ABC    | 123    |
|    4 | GHI    | 432    |
|    5 | NULL   | 444    |
+------+--------+--------+

要连接选定的列(field1 和 field2),我可以使用以下查询:

select coalesce(field1, '') || ' ' || coalesce(field2::text, '') from xyz;

这给出了以下结果:

ABC 123
GHI 432
222

如何将所有结果行合并为一行?我想实现以下目标

ABC 123, GHI 432, 444

SQL Fiddle

【问题讨论】:

    标签: sql postgresql postgresql-9.5 string-aggregation


    【解决方案1】:

    你可以使用 array_agg

    SELECT array_agg(coalesce(field1, '') || ' ' || coalesce(field2::text, '') )
    FROM xyz
    

    http://sqlfiddle.com/#!17/535f6/7

    【讨论】:

    猜你喜欢
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2011-08-01
    • 2013-12-25
    • 2018-11-14
    • 2022-01-13
    相关资源
    最近更新 更多