庫存在各生產訂單間分配
IF OBJECT_ID(‘Tempdb..#T1‘,‘U‘) IS NOT NULL DROP TABLE #T2
IF OBJECT_ID(‘Tempdb..#TEMP‘,‘U‘) IS NOT NULL DROP TABLE #TEMP
DECLARE @guid VARCHAR(100)
SET @guid = NEWID()
EXEC [U_P_STOCK2NEED_TABLE] @guid
SELECT * INTO #TEMP FROM U_T_STOCK2NEED WHERE [GUID] = @guid
SELECT T0.DocEntry,
ROW_NUMBER()OVER(PARTITION BY T1.ItemCode ORDER BY T0.DueDate) Lineid,
T0.Status,T0.PostDate,T0.DueDate,T0.PickRmrk ,T0.ItemCode Fanther,T0.PlannedQty FtPlanQty,T0.CmpltQty,T0.U_QtyEnd,
T1.LineNum,T1.ItemCode ChildCode,T1.PlannedQty ChdPlanQty,T1.IssuedQty,T1.PlannedQty-T1.IssuedQty OrderQty,
0 AS QtyFP,
ISNULL(U0.可用庫存,0) AS SurplQty,
U0.[溢缺.庫存],
U0.[采購/生產在途] ,
CASE WHEN U0.[溢缺.庫存]>0 THEN 0
WHEN U0.[溢缺.庫存]<0 AND (U0.[溢缺.庫存]+U0.[采購/生產在途])>0 THEN 0
WHEN U0.[溢缺.庫存]<0 AND (U0.[溢缺.庫存]+U0.[采購/生產在途])<0 THEN (U0.[溢缺.庫存]+U0.[采購/生產在途])
END 待生產量
INTO #T1
JOIN WOR1 T1 ON T0.DocEntry =T1.DocEntry
JOIN OITM R0 ON T0.ItemCode =R0.ItemCode
JOIN OITM R1 ON T1.ItemCode =R1.ItemCode
LEFT JOIN #TEMP U0 ON T1.ItemCode =U0.物料編號
WHERE R0.QryGroup49=‘Y‘ AND T0.Status IN (‘R‘,‘P‘) AND (T1.PlannedQty-T1.IssuedQty)>0
ORDER BY T0.ItemCode,T0.DueDate
--逐行累計數量(含本行)
SELECT T0.DocEntry,
T0.Lineid,
T0.ChildCode,
MAX(T0.OrderQty) OrderQty,
MAX(T0.SurplQty) SurplQty,
SUM(T1.OrderQty) NeedQty,
CASE WHEN MAX(T0.SurplQty)-SUM(T1.OrderQty)>=0 THEN MAX(T0.SurplQty)-SUM(T1.OrderQty)
ELSE 0 END KfbQty
INTO #T2
FROM #T1 T0
LEFT JOIN #T1 T1 ON T0.ChildCode = T1.ChildCode AND T0.[Lineid] >= T1.Lineid
GROUP BY T0.DocEntry,T0.Lineid,T0.ChildCode
UPDATE #T1 SET QtyFP = CAST(T21.QtyFP AS DECIMAL(19,6)),SurplQty=T21.KfbQty
FROM #T1 T20
LEFT JOIN (
--區間劃分確定是否足夠分配 累計量比總量大 隨便分; 總量在上行累計量和本行累計量之間 總量-上行累計量 分一點;總量小於上行累計量,沒的分。
SELECT T10.DocEntry,
T10.Lineid,
T10.ChildCode,
CASE WHEN T10.KfbQty >0 THEN T10.OrderQty
WHEN T10.KfbQty >0 AND T10.KfbQty<T10.NeedQty THEN T10.KfbQty
WHEN T10.KfbQty=0 AND T10.KfbQty<T10.NeedQty THEN ISNULL(T11.KfbQty,0)
ELSE 0.00 END [QtyFP],
T10.KfbQty
FROM #T2 T10 LEFT JOIN #T2 T11 ON T10.ChildCode =T11.ChildCode AND T11.Lineid =T10.Lineid-1
)T21 ON T20.Lineid= T21.Lineid AND T20.ChildCode =T21.ChildCode
SELECT U0.DocEntry 生產訂單號
,U0.Lineid 行號
,CASE WHEN U0.Status=‘R‘ THEN ‘已審核‘ ELSE ‘已計劃‘ END 狀態
,U0.PostDate 訂單日期
,U0.DueDate 完工日期
,U0.PickRmrk 業務訂單號
,U0.Fanther 產品編號
,U0.FtPlanQty 訂單量
,U0.CmpltQty 完工量
,U0.U_QtyEnd 最終完工
,U0.LineNum 子件行號
,U0.ChildCode 子件料號
,U0.ChdPlanQty 計劃發料
,U0.IssuedQty 實際已發
,U0.OrderQty 待發料量
,U0.ValidQty 可用庫存
,U0.QtyFP 分配量
,U0.SurplQty 剩余分配量
,U0.[溢缺.庫存] 總庫存
,U0.[采購/生產在途] 總在途
,U0.待生產量 待補工單量
,U1.ItemName 子件名稱
FROM #T1 U0
LEFT JOIN OITM U1 ON U0.ChildCode =U1.ItemCode
ORDER BY U0.DueDate
DROP TABLE #TEMP
DROP TABLE #T1
DROP TABLE #T2
庫存在各生產訂單間分配