
sqlserver 怎么将查询出来的某列值相同的记录的另一列的值拼起来 求sql 语句怎么写
如tab表ab11001210023100241001怎么将b列值相同的a列用分号拼起来结果如下:1,42,3上面结果如下:1001(1,4)1002(2,3)如果ab1...
如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) 展开
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) 展开
2个回答
展开全部
我有一个方法可以实现。但是是用两个SQL语句,来两次循环就可以解决。具体思想给你说一下,你自己搞定吧。
select distinct(b) from tab 查找出不同的b中的字段,然后循环
select a from tab where b="上面那个循环的数值b" 然后循环
就可以解决这个问题了。思想是这样,最好自己亲手做出来。
select distinct(b) from tab 查找出不同的b中的字段,然后循环
select a from tab where b="上面那个循环的数值b" 然后循环
就可以解决这个问题了。思想是这样,最好自己亲手做出来。
展开全部
不用那么麻烦,看我的:
(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。
(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。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |