SQL Server使用SQL语句把重复行数据合并为一行并用逗号分隔的解决办法
这篇文章主要为大家详细介绍了SQL Server使用SQL语句把重复行数据合并为一行并用逗号分隔的简单示例,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!
一.定义表变量
代码如下:
DECLARE @T1 table
(
UserID int ,
UserName nvarchar(50),
CityName nvarchar(50)
);
insert into @T1 (UserID,UserName,CityName) values (1,'a','上海')insert into @T1 (UserID,UserName,CityName) values (2,'b','北京')insert into @T1 (UserID,UserName,CityName) values (3,'c','上海')insert into @T1 (UserID,UserName,CityName) values (4,'d','北京')insert into @T1 (UserID,UserName,CityName) values (5,'e','上海')
select * from @T1
-----最优的方式SELECT CityName,STUFF((SELECT ',' + UserName FROM @T1 subTitle WHERE CityName=A.CityName FOR XML PATH('')),1, 1, '') AS AFROM @T1 AGROUP BY CityName
----第二种方式SELECT B.CityName,LEFT(UserList,LEN(UserList)-1)FROM ( SELECT CityName,(SELECT UserName+',' FROM @T1 WHERE CityName=A.CityName FOR XML PATH('')) AS UserList FROM @T1 A GROUP BY CityName ) B
stuff(select ',' + fieldname from tablename for xml path('')),1,1,'')
效果图:
【图片暂缺】
注:关于SQL Server使用SQL语句把重复行数据合并为一行并用逗号分隔的简单示例的内容就先介绍到这里,更多相关文章的可以留意