读书人

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

发布时间: 2012-09-14 23:00:48 作者: rapoo

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

读书人网 >SQL Server

热点推荐