To achieve this type of calculation in SQL, where you need a recursive dependency on previous rows, you can utilize a recursive common table expression (CTE). Here's how you can approach your problem step-by-step:
Steps: Base Case (Initialization): The first row will be computed directly since there's no prior week to reference.
Recursive Case: For subsequent rows, compute:
Stock: Add the order_amount from two weeks ago (based on delivery_time) to the current week's stock. Order Amount: Check if stock - needed < safety_stock. If true, an order is placed (order_amount is added to stock in the delivery week). Delivery Logic: Use the delivery_time column to identify when the order is delivered and update the stock accordingly.