将多个记录组合到sql db2中的一个单元格中

时间:2014-05-22 12:34:54

标签: sql sybase

我有一个有两列的表 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

请帮忙。

1 个答案:

答案 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