I am trying to write a sql query using TSQL to get the running total Quantity of columns, I am by no means good at writing queries, but unfortunately here i am…bascially after everything i have a temp table that has the data i need
SELECT DISTINCT
MQ.[Company]
,MQ.[status]
,MQ.[Facility]
,MQ.[ItemCode]
,MQ.[Style]
,MQ.[Description]
,CONVERT(date, MQ.[PlannedDate], 101) AS [PlannedDate]
,MONTH(CONVERT(date, CONVERT(date, MQ.[PlannedDate], 101))) AS [PlannedDateMonth]
,YEAR(CONVERT(date, CONVERT(date, MQ.[PlannedDate], 101))) AS [PlannedDateYear]
,MQ.[On-HandApprove]
,MQ.[TransactionQuantity]
,MQ.[OrderNumber]
,MQ.[OrderLineNumber]
,MQ.[WorkOrderNumber]
,MQ.[PurchaseOrderNumber]
,MQ.[PurchaseOrderLineNumber]
,MQ.[OrderQuantity]
,MQ.[InTransit]
,MQ.[OutstandingQuantity]
,MQ.[PODueDate]
FROM #MainQuery MQ
WHERE MQ.Facility IN (@Facility) AND
MQ.[ItemCode] IN (SELECT DISTINCT itno FROM #MP)
AND MQ.[Company] = @Company
ORDER BY MQ.[ItemCode], CONVERT(date, MQ.[PlannedDate], 101)
However i am trying to get a “Running Total Quantity” based on the Item Code, and which Facility it is located at. created some fake data as i’m better explaining with pictures than i am words lol
The formula to get it would be
For the first record per Itemcode/Facility:
(On-HandApprove – TransactionQuantity + OutstandingQuantity) = Running Total Quantity
For the next records per Itemcode/Facility:
(Previous Running Total Quantity – TransactionQuantity + OutstandingQuantity) = Running Total Quantity
So this is basically what i’m after, i have tried this
(SUM(MQ.[TransactionQuantity]) OVER (PARTITION BY MQ.[ItemCode],MQ.[Facility] ORDER BY CONVERT(date, MQ.[PlannedDate], 101) ROWS UNBOUNDED PRECEDING) - ISNULL(MQ.[On-HandApprove], 0) ) + ISNULL(MQ.[OutstandingQuantity], 0) AS [RunningTotalTransactionQuantity]
and a few different alterations of it but cant seem to get it the way i need it…..please help!!