sqlserver 怎么将查询出来的某列值相同的记录的另一列的值拼起来 求sql 语句怎么写

如tab表
a b
1 1001
2 1002
3 1002
4 1001
怎么将b列值相同的a列用分号拼起来
结果如下 :
1,4
2,3
上面结果如下 :
1001 (1,4)
1002 (2,3)
如果
a b
1 1001
2 1002
3 1003
4 1002
结果如下:
1001 (1)
1002 (2,4)
1003 (3)

我有一个方法可以实现。但是是用两个SQL语句,来两次循环就可以解决。具体思想给你说一下,你自己搞定吧。
select distinct(b) from tab 查找出不同的b中的字段,然后循环
select a from tab where b="上面那个循环的数值b" 然后循环
就可以解决这个问题了。思想是这样,最好自己亲手做出来。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-03-27
不用那么麻烦,看我的:
(1) select b,b+'('+stuff((select ','+a from tab t2 where t2.b=t1.b for xml path('')),1,1,'')+')' as result from tab t1 group by b
(2) select b,'('+stuff((select ','+a from tab t2 where t2.b=t1.b for xml path('')),1,1,'')+')' as result from tab t1 group by b
(3) select b+'('+stuff((select ','+a from tab t2 where t2.b=t1.b for xml path('')),1,1,'')+')' as result from tab t1 group by b
看哪个你要的。
至于为什么可以这样,请百度T-SQL的for xml path。本回答被提问者采纳
相似回答