日期:2014-05-18  浏览次数:20484 次

如何将一张表中有着相同ID的某个字段的所有值在查询结果中放入一个字段
A B C
1 1 王
2 2 李
3 3 赵
4 3 钱
5 3 孙
可以有查询语句可以达到如下效果吗:
B C
1 王
2 李
3 赵,钱,孙

------解决方案--------------------
SQL code
select B , C=
stuff((select ','+C from tablename t where B =tablename.B for xml path('')), 1, 1, '') 
from tablename 
group by B

------解决方案--------------------
SQL code

declare @tb table (id int, value varchar(10)) 
insert into @tb values(1, 'aa') 
insert into @tb values(1, 'bb') 
insert into @tb values(2, 'aaa') 
insert into @tb values(2, 'bbb') 
insert into @tb values(2, 'ccc')



select id , [ccname]=
stuff((select ','+[value] from @tb t where id =tv.id for xml path('')), 1, 1, '') 
from @tb as tv
group by id 
/*
id    ccname
1    aa,bb
2    aaa,bbb,ccc
*/