使数据所有数据都返回一行

时间:2015-05-26 21:10:35

标签: sql row coalesce

我有一张桌子,我的数据如下:

ID      name        contact
1234    company XYZ jane@xyz.com
1234    company XYZ john@xyz.com
1234    company XYZ sue@xyz.com
1234    company XYZ mark@xyz.com
1234    company XYZ jack@xyz.com
1234    company XYZ alex@xyz.com

但我需要这个结果集:

ID      name         contact
12345   company XYZ  jane@xyz.com,john@xyz.com,sue@xyz.com,mark@xyz.com,jack@xyz.com,alex@xyz.com

1 个答案:

答案 0 :(得分:0)

以下是示例:

SELECT  ID, Name,
        STUFF((SELECT ',' + Contact
               FROM SomeTable 
               WHERE ID = t.ID
               FOR XML PATH('')),1,1,'') Contacts
FROM SomeTable t
GROUP BY ID, Name