如何将一张表中有着相同ID的某个字段的所有值在查询结果中放入一个字段
A B C
1 1 王
2 2 李
3 3 赵
4 3 钱
5 3 孙
可以有查询语句可以达到如下效果吗:
B C
1 王
2 李
3 赵,钱,孙
[解决办法]
select B , C=stuff((select ','+C from tablename t where B =tablename.B for xml path('')), 1, 1, '') from tablename group by B
[解决办法]
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 tvgroup by id /*id ccname1 aa,bb2 aaa,bbb,ccc*/