首页 >数据库 >mysql教程 >如何使用 SQL 递归 CTE 减少合并批次数量?

如何使用 SQL 递归 CTE 减少合并批次数量?

DDD
DDD原创
2025-01-10 11:46:42430浏览

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