我有一个有两列的表 id和评论:
id comment
1 test1
1 test2
1 test3
2 test4
3 test5
我们如何使用sql db2查询实现以下功能: id comment
1 test1,test2,test3
2 test4
3 test5
请帮忙。
答案 0 :(得分:1)
您可以使用LISTAGG:
SELECT id, LISTAGG(comment, ',') as comments
FROM myTable
GROUP BY id
或者你可以试试:
SELECT id,
SUBSTR(XMLSERIALIZE(XMLAGG(XMLTEXT(CONCAT(', ', comment))) as VARCHAR(1024)), 3)
FROM myTable
GROUP BY id
或尝试:
SELECT id, GROUP_CONCAT(comment SEPARATOR ", ") as comments
FROM myTable
GROUP BY id
或者:
SELECT CAT.id,
STUFF((SELECT ',' + SUB.comment AS [text()]
FROM MyTable SUB
WHERE SUB.id = CAT.id
FOR XML PATH('')
), 1, 1, '' ) AS Comments
FROM MyTable CAT