I am trying to write a T-SQL query to get the running total quantity of columns, I am by no means good at writing queries, but unfortunately here I am… basically after everything I have a temp table that has the data I need
SELECT
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
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
Facility | ItemCode | PlannedDate | On-HandApprove | TransactionQuantity | OutstandingQuantity | Running Total Quantity |
---|---|---|---|---|---|---|
P00 | 07J000061COY050 | 2/23/2024 | 1189 | 984 | 984 | 1189 |
P00 | 07J000061COY050 | 5/10/2024 | 1189 | -192 | 0 | 1381 |
P00 | 07J000061COY050 | 5/10/2024 | 1189 | 192 | 0 | 997 |
P00 | 07J000061COY050 | 5/10/2024 | 1189 | 312 | 312 | 997 |
P00 | 07J000061COY050 | 6/14/2024 | 1189 | -24 | 0 | 1021 |
P00 | 07J000061COY050 | 6/14/2024 | 1189 | 24 | 0 | 997 |
P00 | 07J000061COY051 | 2/23/2024 | 1500 | 500 | 984 | 1984 |
P00 | 07J000061COY051 | 5/10/2024 | 1500 | -192 | 0 | 2176 |
P00 | 07J000061COY051 | 5/10/2024 | 1500 | 192 | 0 | 1984 |
D00 | 07J000061COY051 | 5/10/2024 | 1500 | 312 | 312 | 1500 |
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!!
5