I am working in Azure Synapse and trying to create a query to calculate the daily quantity of each item for each day in a date range. The starting qty should include the sum of all entries before that date. For Example, if we want to see daily inventory from 2023-01-01 through 2023-01-06, the first row that would be 2023-01-01 would contain the sum of the items Qty from the start date plus anything before that start date.
Below is an example of my table: Inventory
ItemId | Date | Qty |
---|---|---|
A002 | 2022-12-10 | 1 |
A001 | 2022-12-30 | 4 |
A001 | 2023-01-01 | 5 |
A001 | 2023-01-01 | -2 |
A001 | 2023-01-03 | 4 |
A002 | 2023-01-02 | 3 |
A002 | 2023-01-05 | 2 |
A002 | 2023-01-06 | -1 |
Using the example table would expect an outcome of the below
ItemId | Date | Qty |
---|---|---|
A001 | 2023-01-01 | 7 |
A001 | 2023-01-02 | 7 |
A001 | 2023-01-03 | 11 |
A001 | 2023-01-04 | 11 |
A001 | 2023-01-05 | 11 |
A001 | 2023-01-06 | 11 |
A002 | 2023-01-01 | 1 |
A002 | 2023-01-02 | 4 |
A002 | 2023-01-03 | 4 |
A002 | 2023-01-04 | 4 |
A002 | 2023-01-05 | 6 |
A002 | 2023-01-06 | 5 |
Below is the latest query I have tried and I seem to be getting the starting qty fine but looks dates after are not and I am trying to get an entry for each day.
WITH Inventory AS (
SELECT ItemId, Date, SUM(Qty) AS TotalQuantity
FROM Inventory
WHERE Date <= '2023-01-07'
GROUP BY ItemId, Date
), StartingInventory AS (
SELECT ItemId, SUM(Qty) AS StartingQuantity
FROM Inventory
WHERE DatePhysical < '2023-01-01'
GROUP BY ItemId
)
SELECT i.ItemId, i.Date, SUM(i.TotalQuantity) +
COALESCE(s.StartingQuantity, 0) AS DailyTotalInventory
FROM Inventory i
LEFT JOIN StartingInventory s ON i.ItemId = s.ItemId
WHERE i.DatePhysical BETWEEN '2023-01-01' AND '2023-01-07'
GROUP BY i.ItemId, i.Date, s.StartingQuantity
ORDER BY i.ItemId, i.Date
And another attempt at this query seem to get the starting date calculating correctly however following dates are not and a row is not generated for each date in the date range
WITH AllDates AS (
SELECT DISTINCT d.DatePhysical, i.ItemId
FROM Inventrans i
CROSS JOIN (
SELECT DISTINCT DatePhysical
FROM InvenTrans
WHERE DatePhysical BETWEEN '2023-01-01' AND '2023-01-07'
) d
), Inventory AS (
SELECT ItemId, DatePhysical, SUM(Qty) AS TotalQuantity
FROM InvenTrans
WHERE DatePhysical <= '2023-01-07'
GROUP BY ItemId, DatePhysical
), StartingInventory AS (
SELECT ItemId, SUM(Qty) AS StartingQuantity
FROM Inventrans
WHERE DatePhysical < '2023-01-01'
GROUP BY ItemId
)
SELECT d.DatePhysical, d.ItemId, COALESCE(SUM(i.TotalQuantity), 0) + COALESCE(s.StartingQuantity, 0) AS DailyTotalInventory
FROM AllDates d
LEFT JOIN Inventory i ON d.ItemId = i.ItemId AND d.DatePhysical = i.DatePhysical
LEFT JOIN StartingInventory s ON d.ItemId = s.ItemId
WHERE d.DatePhysical BETWEEN '2023-01-01' AND '2023-01-07'
GROUP BY d.DatePhysical, d.ItemId, s.StartingQuantity
ORDER BY d.ItemId, d.DatePhysical