SQL 经典行转列,外加点小难度
脚本如下
with t as
(select NumID,rtrim(SkuID)+':'+rtrim(Stock) 'Sku_Stock',
(row_number() over(partition by NumID order by getdate())-1)/20 'rn'
from tab)
select a.NumID,
stuff((select ';'+b.Sku_Stock from t b
where b.NumID=a.NumID and b.rn=a.rn
for xml path('')),1,1,'') 'Sku_Stock'
from t a
group by a.NumID,a.rn
/*
NumID Sku_Stock
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
23940 3983:4;3984:5;3985:6;3986:7;3987:8;3988:9;3989:10;3990:11;3991:12;3992:13;3993:14;3994:15;3995:16;3996:17;3997:18;3998:19;3999:20;4000:21;4001:22;4002:23
23940 4003:24;4004:25
33950 33:4;34:5;35:6
36951 53:4
(4 row(s) affected)
*/
;WITH t AS
(
SELECT *,
(select count(*) from tab t2
where t2.numid = t1.numid and
t2.skuid <=t1.skuid) as rownum
FROM tab t1
)
,tt AS
(
select NumID,SkuID,Stock,rownum,
(rownum -1) / 20 as rownum_group
from t
)
SELECT NumID,
STUFF(
(
SELECT ';'+cast(SkuID as varchar)+':'+cast(Stock as varchar)
FROM tt tt2
WHERE tt2.NumID=tt1.NumID AND
tt2.rownum_group = tt1.rownum_group
FOR XML PATH('')
),
1,1,''
) as sku_stock
FROM tt tt1
GROUP BY NumID,rownum_group
/*
NumIDsku_stock
239403983:4;3984:5;3985:6;3986:7;3987:8;3988:9;3989:10;3990:11;3991:12;3992:13;3993:14;3994:15;3995:16;3996:17;3997:18;3998:19;3999:20;4000:21;4001:22;4002:23
239404003:24;4004:25
3395033:4;34:5;35:6
3695153:4
*/