CREATE TABLE #table(ID int, Qty Decimal(11,3))
INSERT INTO #table(ID,Qty)
VALUES (1, 1),
(2, 5),
(3, 5),
(4, 10);
Declare @q int = 12;
SELECT id, Qty
,(@q - cumvalue1 ) as RemainingQtyForNextRow
,(CASE When @q - cumvalue1 > 0 THEN 0 ELSE cumvalue1 - @q END) as RemainingQty
FROM (SELECT id, Qty,
sum(Qty) over (order by id) as cumvalue1
FROM #table t
) t;