首頁 >資料庫 >mysql教程 >如何使用 SQL 遞歸 CTE 減少合併批次數量?

如何使用 SQL 遞歸 CTE 減少合併批次數量?

DDD
DDD原創
2025-01-10 11:46:42470瀏覽

How to Reduce Pooled Lot Quantity Using SQL Recursive CTE?

使用 SQL 遞歸 CTE 減少合併批次數量

此 SQL Server 2005 解決方案採用遞歸公用表表達式 (CTE),根據消耗資料迭代減少合併批次數量。 此流程可有效處理池內多個批次的消耗量超過可用數量的情況。

這是 SQL 程式碼:

<code class="language-sql">-- Sample data setup
DECLARE @Pooled_Lots AS TABLE (
  Id INT,
  Pool INT,
  Lot INT,
  Quantity INT
);

INSERT INTO @Pooled_Lots (Id, Pool, Lot, Quantity) VALUES
(1, 1, 1, 5),
(2, 1, 2, 10),
(3, 1, 3, 4),
(4, 2, 1, 7),
(5, 3, 1, 1),
(6, 3, 2, 5);

DECLARE @Pool_Consumption AS TABLE (
  Id INT,
  PoolId INT,
  QuantityConsumed INT
);

INSERT INTO @Pool_Consumption (Id, PoolId, QuantityConsumed) VALUES
(1, 1, 17),
(2, 2, 8),
(3, 3, 10);


-- Recursive CTE to calculate remaining quantities
WITH LotQuantities AS (
    SELECT 
        PL.Pool, 
        PL.Lot, 
        PL.Quantity, 
        PC.QuantityConsumed,
        PL.Quantity as RunningQuantity,
        PC.QuantityConsumed as RemainingDemand,
        CASE WHEN PL.Quantity >= PC.QuantityConsumed THEN 0 ELSE PC.QuantityConsumed - PL.Quantity END as SurplusOrDeficit
    FROM @Pooled_Lots PL
    LEFT JOIN @Pool_Consumption PC ON PL.Pool = PC.PoolId
    WHERE PL.Lot = 1 -- Start with the first lot in each pool

    UNION ALL

    SELECT 
        lq.Pool, 
        PL.Lot, 
        PL.Quantity, 
        lq.QuantityConsumed,
        CASE WHEN lq.RemainingDemand > PL.Quantity THEN lq.RunningQuantity + PL.Quantity ELSE lq.QuantityConsumed END,
        CASE WHEN lq.RemainingDemand > PL.Quantity THEN lq.RemainingDemand - PL.Quantity ELSE 0 END,
        CASE WHEN lq.RemainingDemand > PL.Quantity THEN 0 ELSE lq.RemainingDemand - (lq.RunningQuantity + PL.Quantity) END
    FROM LotQuantities lq
    JOIN @Pooled_Lots PL ON lq.Pool = PL.Pool AND PL.Lot = lq.Lot + 1
    WHERE lq.RemainingDemand > 0
)
SELECT * FROM LotQuantities;</code>

產生的資料集顯示消耗扣除後每批的剩餘數量。 CTE 遞歸地處理每個池中的批次,直到完全考慮到消耗的數量。 請注意,SurplusOrDeficit 中的負值表示不足。

以上是如何使用 SQL 遞歸 CTE 減少合併批次數量?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn