如果我有一个有 2 列的表
text | id
---------
aaa | 1
bbb | 1
eee | 1
mmm | 2
zzz | 2
...
是否可以编写一个按 id 分组并输出以下结果的查询:
id | text
------------------
1 | aaa, bbb, eee
2 | mmm, zzz
...
谢谢!
试试这个,
SELECT ID,
SUBSTR(xmlserialize(xmlagg(xmltext(CONCAT( ', ',text))) as VARCHAR(1024)), 3)
FROM tableName
GROUP BY ID;
使用listagg
DB2 中的函数:
select id, listagg(text, ', ') as text
from t
group by id
如果您希望它们按字母顺序排列:
select id, listagg(text, ', ') within group (order by text) as text
from t
group by id