追蹤多個批次的消耗品庫存
高效率的庫存管理需要精確追蹤合併批次中的消耗品數量。 這就需要一個查詢,根據特定條件準確地從多個批次中扣除消耗量。 所提出的解決方案利用遞歸通用表表達式 (CTE) 來實現此目的。
遞歸 CTE 方法:
此解決方案的核心是遞歸 CTE,巧妙地命名為“Amos”,它會迭代池中的批次。 首先用第一批來初始化每個池。 然後,CTE 遞歸處理後續批次,動態更新消耗數量。
對於每一批次,CTE 根據累計消耗計算RunningQuantity
(剩餘數量)和RemainingDemand
(未結數量)。 然後,這些值將用於通知同一池中後續批次的計算。
輸出詳細資訊:
最終結果集提供了每個池和批次的全面細分,包括:
範例實作:
以下範例使用範例資料示範了查詢的功能:
<code class="language-sql">-- Sample Data (Pooled Lots) DECLARE @Pooled_Lots 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); -- Sample Data (Pool Consumption) DECLARE @Pool_Consumption TABLE (Id INT, Pool INT, QuantityConsumed INT); INSERT INTO @Pool_Consumption (Id, Pool, QuantityConsumed) VALUES (1, 1, 17), (2, 2, 8), (3, 3, 10); -- Recursive CTE Query WITH Amos AS ( -- Anchor Member: Initialize with the first lot of each pool SELECT PL.Pool, PL.Lot, PL.Quantity, PC.QuantityConsumed, CASE WHEN PC.QuantityConsumed IS NULL THEN PL.Quantity WHEN PL.Quantity >= PC.QuantityConsumed THEN PL.Quantity - PC.QuantityConsumed ELSE 0 END AS RunningQuantity, CASE WHEN PC.QuantityConsumed IS NULL THEN 0 WHEN PL.Quantity >= PC.QuantityConsumed THEN 0 ELSE PC.QuantityConsumed - PL.Quantity END AS RemainingDemand FROM @Pooled_Lots PL LEFT JOIN @Pool_Consumption PC ON PC.Pool = PL.Pool WHERE Lot = 1 UNION ALL -- Recursive Member: Process subsequent lots SELECT PL.Pool, PL.Lot, PL.Quantity, CTE.QuantityConsumed, CASE WHEN CTE.RunningQuantity + PL.Quantity >= CTE.RemainingDemand THEN CTE.RunningQuantity + PL.Quantity - CTE.RemainingDemand ELSE 0 END, CASE WHEN CTE.RunningQuantity + PL.Quantity >= CTE.RemainingDemand THEN 0 ELSE CTE.RemainingDemand - CTE.RunningQuantity - PL.Quantity END FROM Amos CTE JOIN @Pooled_Lots PL ON PL.Pool = CTE.Pool AND PL.Lot = CTE.Lot + 1 ) -- Final Result Set SELECT *, CASE WHEN Lot = (SELECT MAX(Lot) FROM @Pooled_Lots WHERE Pool = Amos.Pool) THEN RunningQuantity - RemainingDemand ELSE NULL END AS SurplusOrDeficit FROM Amos ORDER BY Pool, Lot;</code>
這個精緻的解釋和範例讓您更清楚地了解遞歸 CTE 的功能及其在庫存管理中的應用。 SurplusOrDeficit
計算現在明確與每個池中的最後一批相關聯。
以上是遞歸 CTE 如何分配和追蹤合併批次中的消耗品數量,提供剩餘數量和未完成數量的詳細分類?的詳細內容。更多資訊請關注PHP中文網其他相關文章!