码迷,mamicode.com
首页 > 其他好文 > 详细

将多行数据变一行

时间:2015-08-18 15:34:21      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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 ‘,‘ + UserName FROM @T1 subTitle
SELECT ‘,‘ +UserName FROM @T1 subTitle FOR XML PATH(‘‘)
SELECT STUFF((SELECT ‘,‘ + UserName FROM @T1 subTitle FOR XML PATH(‘‘)),1, 1, ‘‘)

SELECT CityName,STUFF((SELECT ‘,‘ + UserName FROM @T1 subTitle WHERE CityName=A.CityName FOR XML PATH(‘‘)),1, 1, ‘‘) AS A
FROM @T1 A GROUP BY CityName

将多行数据变一行

标签:

原文地址:http://www.cnblogs.com/zhuangke668/p/4739218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!