请高手指点!!那个我select '证书' from UserInfo where UserID=1
结果一个人对应四五个证书的话就出来了四五行,我想一个人的所有证书在一列显示,而且用","隔开,怎么用啊,
拜托各位大侠求解啊。
再次先谢过了!!
一种是利用游标 自己拼接或者客户端做处理吧
第一种:可以到程序里处理;
第二种:首先要确保 一个用户的和一个证书最多是一条数据,而且证书种类要几乎不会变,如果是的话
select (select 证书列 from UserInfo where UserID=1 and 证书列='证书1' )
+','+(select 证书列 from UserInfo where UserID=1 and 证书列='证书2‘)
+','+(select 证书列 from UserInfo where UserID=1 and 证书列='证书3' )
+','+(select 证书列 from UserInfo where UserID=1 and 证书列='证书4' )
依次类推
第三种:游标 但是不推荐 ,速度很慢
declare my_cursor cursor scroll dynamic
for
select 证书列 from UserInfo where UserID=1 order by 证书列
open my_cursor
declare @pname sysname,@str varchar(500)
set @str=''
fetch next from my_cursor into @pname
while(@@fetch_status=0)
begin
set @str=@str+','+@pname
fetch next from my_cursor into @pname
end
close my_cursor
deallocate my_cursor
select @str
还有一种简单的办法。
declare @zhengshu varchar(max)
select @zhengshu=@zhengshu+','+证书 from UserInfo where UserID=1
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 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