I am trying to map inventory using LIFO to determine the dates the orders initially arrived in the inventory to the day that they leave. However, the inventory can go from positive to negative.
For example:
Day 1: purchase 1,000 units; (inventory 1,000 units)
Day 2: purchase 1,000 units; (inventory 2,000 units)
Day 3: sell 500 units; (inventory 1,500 units)
Day 4: purchase 2,000 units; (inventory 3,500 units)
Day 5: sell 3,000 units; (inventory 500 units)
Day 6: sell 10,000 units; (inventory -9,500 units)
I will need to know that Day 5 units come from a minimum date of day 1 and maximum date of day 4. Is there any way to do this in SQL?
UPDATE #TEMP_ORDERS_STEP_2
SET CUMULATIVE_UNITS = UNITS
, REMAINING_UNITS = UNITS
, Min_Inventory_Date = 'n/a'
, Max_Inventory_Date = 'n/a'
WHERE Row_ID = 1
AND CUMULATIVE_SHARES IS NULL
--(30609 row(s) affected)
SELECT DateId, OrderID, ProductCode, ProductType, Units, Row_ID, Inventory, CUMULATIVE_UNITS, Min_Inventory_Date, Max_Inventory_Date
FROM #TEMP_ORDERS_STEP_2 A
JOIN (SELECT * FROM #TEMP_ORDERS_STEP_2 WHERE REMAINING_UNITS IS NOT NULL) B
ON A.ProductCode = B.ProductCode AND A.ProductType = B.ProductType AND A.Row_ID = B.Row_ID + 1
WHERE A.CUMULATIVE_SHARES IS NULL