CREATE TABLE table_a(
rowid nvarchar(8) NULL,--行号
ItemCode nvarchar(48) NULL,--编码
MustQty int NULL,--计划数量
Qty int NULL--实际数量
);
CREATE TABLE table_b(
ItemCode nvarchar(48) NULL,--编码
Qty int NULL--数量
);
insert into table_a(rowid,ItemCode,MustQty,Qty)values('10','10010001',10,0);
insert into table_a(rowid,ItemCode,MustQty,Qty)values('11','10010001',20,0);
insert into table_a(rowid,ItemCode,MustQty,Qty)values('12','10010001',10,0);
insert into table_a(rowid,ItemCode,MustQty,Qty)values('13','10010001',20,0);
insert into table_a(rowid,ItemCode,MustQty,Qty)values('14','10010001',10,0);
insert into table_a(rowid,ItemCode,MustQty,Qty)values('15','10010001',50,0);
insert into table_b(ItemCode,Qty)values('10010001',100);
table_a,table_b通过 ItemCode关联
如何将 table_b Qty 分配到 table_a中的 Qty(按行号顺序,根据计划数量分配)
希望的结果:
rowid ItemCode MustQty Qty
-------- ------------------------------------------------ ----------- -----------
10 10010001 10 10
11 10010001 20 20
12 10010001 10 10
13 10010001 20 20
14 10010001 10 10
15 10010001 50 30
------解决思路----------------------
--认为table_b 不存在多个相同ItemCode的处理方式SQL2005+有效
;WITH T1 AS(
SELECT ROW_NUMBER()OVER(PARTITION BY ItemCode ORDER BY rowid)RN1,*
FROM table_a
)
,CTE AS(
SELECT T1.rowid,T1.ItemCode,T1.MustQty
,CASE WHEN T1.MustQty>T2.Qty THEN T2.Qty ELSE T1.MustQty END Qty
,T1.RN1,T2.Qty-T1.MustQty[Balance]
FROM T1 JOIN table_b T2 ON T1.ItemCode=T2.ItemCode AND T1.RN1=1
UNION ALL
SELECT T1.rowid,T1.ItemCode,T1.MustQty
,CASE WHEN T1.MustQty>T2.[Balance] THEN T2.[Balance] ELSE T1.MustQty END Qty
,T1.RN1,T2.[Balance]-T1.MustQty
FROM T1 JOIN CTE T2 ON T1.ItemCode=T2.ItemCode AND T2.[Balance]>0 AND T1.RN1=T2.RN1+1
)
SELECT rowid,ItemCode,MustQty,Qty FROM CTE
--考虑table_b 也有多个相同ItemCode的处理方式
;WITH T1 AS(
SELECT ROW_NUMBER()OVER(PARTITION BY ItemCode ORDER BY rowid)RN1,*
FROM table_a
)
,T2 AS(
SELECT ROW_NUMBER()OVER(PARTITION BY ItemCode ORDER BY GETDATE())RN2,*
FROM table_b
)
,CTE AS(
SELECT T1.rowid,T1.ItemCode,T1.MustQty
,CASE WHEN T1.MustQty>T2.Qty THEN T2.Qty ELSE T1.MustQty END Qty
,T1.RN1,T2.RN2,T2.Qty-T1.MustQty[Balance]
FROM T1 JOIN T2 ON T1.ItemCode=T2.ItemCode AND T1.RN1=1 AND T2.RN2=1
UNION ALL
SELECT T1.rowid,T1.ItemCode,T1.MustQty
,CASE WHEN T1.MustQty>T2.[Balance] THEN T2.[Balance] ELSE T1.MustQty END Qty
,T1.RN1,T2.RN2,T2.[Balance]-T1.MustQty
FROM T1 JOIN CTE T2 ON T1.ItemCode=T2.ItemCode AND T2.[Balance]>0 AND T1.RN1=T2.RN1+1
UNION ALL
SELECT T1.rowid,T1.ItemCode,T1.MustQty
,CASE WHEN -T1.[Balance]>T2.Qty THEN T2.Qty ELSE -T1.[Balance] END Qty
,T1.RN1,T2.RN2,T2.Qty+T1.[Balance]
FROM CTE T1 JOIN T2 ON T1.ItemCode=T2.ItemCode AND T1.[Balance]<0 AND T2.RN2=T1.RN2+1
UNION ALL
SELECT T1.rowid,T1.ItemCode,T1.MustQty
,CASE WHEN T1.MustQty>T2.Qty THEN T2.Qty ELSE T1.MustQty END
,T1.RN1,T2.RN2,T2.Qty-T1.MustQty[Balance]
FROM CTE T0 JOIN T1 ON T0.ItemCode=T1.ItemCode AND T0.[Balance]=0 AND T1.RN1=T0.RN1+1
JOIN T2 ON T1.ItemCode=T2.ItemCode AND T2.RN2=T0.RN2+1
)
SELECT rowid,ItemCode,MustQty,Qty FROM CTE