-1
我在這裏是新的,我想出了一個場景,我必須從有調度的地方取出數量。例如我有下表從更高的發貨數量從Id取出數量
ID SKU QtyRec QTYDisp
1 001A 50 0
2 001A 50 10
3 001A 50 20
4 001A 50 0
我已經拿出40數量。它應該首先從ID 3挑然後ID 2,然後從1或4由於調度量大於3然後2.但是,在我目前的情況是,從ID 1
DECLARE @Data table (Id int identity(1,1)
, SKU varchar(10)
, QtyRec INT
,QtyDis INT
)
DECLARE @Qty int = 20
INSERT @Data VALUES
('001A', 50 ,0),
('001A', 50,10),
('001A', 50 ,20),
('001A', 50,0)
;WITH sumqty AS
(
SELECT *, SUM(QtyRec) OVER (PARTITION BY SKU ORDER BY Id) AS TotalQty FROM @Data
)
,takeqty AS (
SELECT *,
CASE
WHEN @Qty >= TotalQty THEN QtyRec
ELSE @Qty - ISNULL(LAG(TotalQty) OVER (PARTITION BY SKU ORDER BY Id), 0)
END AS TakeQty
FROM sumqty
)
SELECT * FROM takeqty WHERE TakeQty > 0
它從ID 3取50,其中,因爲它應該採取30從ID 3,因爲subtrac後剩餘量ting QtyRec和QtyDis是30. –
@azeemhafeez,參見編輯... –