select id, stuff((select ','+name from (select distinct id,name from tb) b where b.id=a.id for xml path('')),1,1,'') from (select distinct id,name from tb) a group by id
注意要SQL2005版本以及更高版本才能用奥!
本文介绍了一种使用SQL Server 2005及以上版本的复杂查询技巧,通过`STUFF`和`FOR XML PATH`函数组合实现对指定ID的所有相关名称进行逗号分隔的字符串拼接。
select id, stuff((select ','+name from (select distinct id,name from tb) b where b.id=a.id for xml path('')),1,1,'') from (select distinct id,name from tb) a group by id
注意要SQL2005版本以及更高版本才能用奥!
3943

被折叠的 条评论
为什么被折叠?