Warehouse storage system (FIFO by BBD and date)
Check this solution:

WITH 
cte1 AS ( SELECT *, 
          SUM(CASE WHEN Quantity &gt; 0 
                   THEN Quantity END) OVER (PARTITION BY ItemId 
                                            ORDER BY InventoryDate) incomeQuantity, 
          SUM(Quantity) OVER (PARTITION BY ItemId 
                              ORDER BY InventoryDate) balance
          FROM inventory ),
cte2 AS ( SELECT ItemID, -SUM(Quantity) spent
          FROM inventory
          WHERE Quantity &lt; 0
          GROUP BY ItemId )
SELECT cte1.ItemID, 
       cte1.InventoryID, 
       cte1.InventoryDate, 
       cte1.Quantity,
       cte1.MoneyValuePerUnit,
       CASE WHEN cte1.incomeQuantity - cte2.spent &lt;= cte1.Quantity
            THEN cte1.incomeQuantity - cte2.spent
            WHEN @amount + cte2.spent &gt;= cte1.incomeQuantity
            THEN Quantity
            ELSE GREATEST(@amount + 
                          cte2.spent - 
                          COALESCE(LAG(cte1.incomeQuantity) OVER (PARTITION BY ItemId 
                                                                  ORDER BY InventoryDate), 0), 0)  
            END expense
FROM cte1
JOIN cte2 USING (ItemId)
WHERE cte1.incomeQuantity &gt; cte2.spent
  AND cte1.Quantity &gt; 0
ORDER BY cte1.InventoryDate


where @amount - the amount of good (itemId) which must be sold. The variable is used because only one itemId is present in data, really this must be a joined table order (itemId unique, amount), which contains the amount for each good to be sold in the order.

fiddle - test it carefully in all possible datasets. But please note - the query does not show that the requested quantity is greater than the stock balance. It also does not take into account the value of BBU if it is not NULL, add the appropriate sorting level.