当前位置: 代码迷 >> Sql Server >> 求sql拼接组合字段,该怎么解决
  详细解决方案

求sql拼接组合字段,该怎么解决

热度:106   发布时间:2016-04-27 11:11:51.0
求sql拼接组合字段
info表

id cust_num compCode
1 a 20000001
2 b 20000002


tpm表

cust_num name
a 电脑
a 电视机
b 电视机
b 电冰箱
b 洗衣机

查询出来的结果

cust_num compcode product
a 20000001 电脑,电视机
b 20000002 电视机,电冰箱,洗衣机

------解决方案--------------------
SQL code
--开始查询select cust_num,compCode,product=stuff((select ','+name from tpm                                         where t.cust_num=cust_num for xml path('')),1,1,'') from info t--测试结果/*cust_num compCode    product-------- ----------- -----------------------a        20000001    电脑,电视机b        20000002    电视机,电冰箱,洗衣机*/
------解决方案--------------------
探讨
SQL code

--开始查询
select cust_num,compCode,product=stuff((select ','+name from tpm
where t.cust_num=cust_num for xml path('')),1,1,'')
from info t
--测试结果……
  相关解决方案