日期:2014-05-17  浏览次数:20424 次

求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
--测试结果……