--测试数据
create table tab
(
NumID int,
SkuID varchar(max),
Stock varchar(max)
)
go
declare @i int
set @i=1
while @i<23
begin
insert into tab (NumID,SkuID,Stock) values ('23940',3982+@i,3+@i)
set @i=@i+1
end
declare @k int
set @k=1
while @k<4
begin
insert into tab (NumID,SkuID,Stock) values ('33950',32+@k,3+@k)
set @k=@k+1
end
declare @n int
set @n=1
while @n<2
begin
insert into tab (NumID,SkuID,Stock) values ('36951',52+@n,3+@n)
set @n=@n+1
end
--select * from tab
需求:将tab表中的数据进行分组合并,合并规则如下:将相同NumID的数据进行合并,每行最多合并20行tab中的数据,超出20行则另插入一行。
结果要求如下图所示。
解答:
--插入临时表
select NumID,SkuID,Stock,row_number() over(order by NumID) as rn,
(row_number() over(order by NumID)-1)/20 as kk into #tab from tab
select * from #tab
先将原数据插入临时表,进行处理,得到如下结果:
kk字段是为了进行分组
SELECT B.NumID,LEFT(StuList,LEN(StuList)-1) as Sku_Stock FROM (
SELECT NumID,
(SELECT SkuID+':'+Stock+',' FROM #tab
WHERE NumID=A.NumID and kk=A.kk
FOR XML PATH('')) AS StuList
FROM #tab A
GROUP BY NumID,kk
) B
得到结果数据: