开发者

t-sql combine column values

开发者 https://www.devze.com 2023-01-08 20:38 出处:网络
Based on the following table IDDescriptionReleateID ----------------------------------- 1some desc1.50 1some desc1.60

Based on the following table

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

How to get the fo开发者_运维技巧llowing output

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

Thanks.


Use the FOR XML trick:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消