将多行的选定列合并为一个字符串[重复]

问题描述 投票:0回答:1

说我有下表:

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个回答
0
投票

你可以使用array_agg

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

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

© www.soinside.com 2019 - 2024. All rights reserved.