t-sql组合列值

时间:2010-07-21 20:49:37

标签: sql sql-server tsql sql-server-2008

基于下表

ID  Description  ReleateID 
-----------------------------------
1   some desc1.   50
1   some desc1.   60
2   some desc2.   50
2   some desc2.   70
3   some desc3.   80

如何获得以下输出

ID  Description   AllRelatedIDs
----------------------------------
1   some desc1.   50,60
2   some desc2.   50,70
3   some desc3.   80

感谢。

1 个答案:

答案 0 :(得分:2)

使用FOR XML技巧:

SELECT t.id, 
       t.description
       STUFF(ISNULL(SELECT ', ' + x.releateid
                      FROM TABLE x
                     WHERE x.id = t.id
                       AND x.description = t.description
                   FOR XML PATH ('')), ''), 1, 2, '')
  FROM TABLE t