I have a table with inventory transactions. A simplified example:
--Inventory Transactions
Date Sold Purchased Balance(not in table)
Today 1 -5
Yesterday 6 -4
5 days ago 5 +2
10 days ago 103 -3
20 days ago 100 +100
Requirements indicate that a report should contain the day since an article had negative balance (stockout). In the example above it would mean yesterday as the answer.
I'm trying to translate this into SQL but I'm having some trouble. I have tried using a CTE:
with Stockouts as (
select getdate() as [Date],
(calculation) as Balance
from [Inventory Transactions]
--some constraints to get the correct article are omitted
union all
select dateadd(dd, -1, Stockouts.[Date]) as [Date],
Stockouts.Balance - (calculation) as Balance
from [Inventory Transactions]
inner join Stockouts
)
But there is the problem that I cannot use a subquery in the recursive part (to find the last transaction before the current one) and an inner join will stop looping when there is no transaction on a certain date (so the dateadd
part will fail as well).
What would be the best approach to solve this issue?