【SQL-分组合并字符串】把相同分组的某个字段合并为同一个字符串(使用函数)

场景:我要把同一个订单同一个客户同一个产品分组合并,同时把该产品所有的库位列举出来,合成一个字符串。

原始数据:

我要得到下面的结果:

SQL如下:

==先建个方法==

create function GetStorehouseCode
(@orderno varchar(100),
 @client varchar(100),
 @goods varchar(100)) 
returns nvarchar(4000)
as
begin
declare @Stocks nvarchar(4000)
set @Stocks=''
select @Stocks=@Stocks+','+Stock from Inventory  
where orderno=@orderno and client=@client and goods=@goods
return stuff(@Stocks,1,1,'')
end

 ==查询==

select orderno,client,goods,dbo.GetStorehouseCode(orderno,client,goods) as Stocks from Inventory
group by orderno,client,goods

  

    上面是其中一种方法。

  待续......

 

posted @ 2016-03-17 16:52  发明创造小能手  阅读(2251)  评论(0编辑  收藏  举报
levels of contents