I imagine this is possible, but extensive research and countless hours haven't paid off.
I'm selling product out of a warehouse. I know when I will be receiving shipments and I have a daily sales forecast (in quantity). I need to calculate the ending inventory. It's basically a running sum of Inventory - Forecast.
The issue is, when I run out of product, I won't have negative inventory the following day, as a running sum would suggest. Inventory will be zero until I receive another shipment. It can go down to zero multiple times in the forecast (far more than in the example below).
Visual of the dataset (desired column in yellow)
SQL Fiddle for cracking the case
Here is my actual query:
SELECT FORECAST_DATE, DAYS_OUT, INBOUND_INVENTORY, FORECAST,
ENDING_INVENTORY AS DESIRED_RESULT,
SUM(INBOUND_INVENTORY) OVER (PARTITION BY NULL ORDER BY DAYS_OUT) -
SUM(FORECAST) OVER (PARTITION BY NULL ORDER BY DAYS_OUT) AS ENDING_INVENTORY
FROM MRP
Columns
Date: The forecast date (starting today)
Days Out: The number of days between today and the forecast date
Inbound Inventory: Product coming in (for today, product here)
Forecast: My projected sales quantity
Ending Inventory: Inbound Inventory - Forecast + If yesterday's Ending Inventory <= 0 then 0 else yesterday's Ending Inventory.
GREATEST(value,0)to change any negative value to 0, andLAG()to retrieve the last row value - Thomas G