sql中怎样把同一张表中相同字段的内容合并为一条记录?并统计数量
客户id 购买产品id
1 123
1 124
1 125
1 126
2 168
2 169
3 123
3 124
3 126
想让表转变成:
客户id 购买产品id
1 123,124,125,126
2 168,169
3 123,124,126
也就是说把一个客户购买的产品合并显示在一条记录中。
然后对123、124、125、126、168、169等等分别进行统计有多少个 展开
12SELECT Customer_ID,Customer_Name,<a href="https://www.baidu.com/s?
wd=STUFF&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3ujRkn1R1uW9hryN-
njF90ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EnHm1rH04rH6snjnkn1mYnjR3n0" target="_blank"
class="baidu-highlight">STUFF</a>((SELECT ','+Linkman_Name FROM Linkman WHERE Customer_ID=Customer.Customer_ID FOR XML <a href=
"https://www.baidu.com/s?wd=PATH&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3ujRkn1R1uW9hryN-
njF90ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EnHm1rH04rH6snjnkn1mYnjR3n0" target="_blank"
class="baidu-highlight">PATH</a>('')),1,1,'') Linkman_Name FROM Customer
扩展资料;
把表名tt换下就可以了购买产品id是字符串类型的话用这个select a.客户id,stuff((select ','+购买产品id from tt b wherea.客户id=b.客户id for XML path('') ),1,1,'') gg from tt a group by a.客户id
如果购买产品id是整型的话,用这个select a.客户id,stuff((select ','+cast(购买产品id as nvarchar(max)) from tt b wherea.客户id=b.客户id for XML path('') ),1,1,'') gg from tt a group by a.客户id
参考资料;百度百科-sql
--你的购买产品id是字符串类型的话用这个
select a.客户id,stuff((select ','+购买产品id from tt b where
a.客户id=b.客户id for XML path('') ),1,1,'') gg from tt a
group by a.客户id
--如果购买产品id是整型的话,用这个
select a.客户id,stuff((select ','+cast(购买产品id as nvarchar(max)) from tt b where
a.客户id=b.客户id for XML path('') ),1,1,'') gg from tt a
group by a.客户id
这个只能合并....不能统计数量.....您能给出统计数量的sql语句不??
兄弟 任何需求都应该是合理的 如果你统计数量的话 那么数量放在哪?你要怎么显示 如果紧跟着购买产品id后面的话,还不如不处理 就像之前那些多行还好看点
能不能具体点啊 ....亲...如果有代码就更好了
create proc test
as
begin
declare @idt int
declare @pdt varchar(5000)
set @pdt=''
create table #t1
(id int)
create table #t2
(id int,
products varchar(5000))
insert into #t1 select id from table
declare cursor dd for select id form #t1
open dd
fetch next from dd into @idt
while @@fetch_status=0
begin
select @pdt=@pdt + table.pdtid +',' from table where id=@idt
insert into #t2 values(@idt,@pdt)
fetch next from dd into @idt
end
close dd
deallocate dd
end
你自己测试着调试吧