MS SQL Server cycle calculation
with cte as (
  select 1 as subId, 100 as A, 0 as X, 10 as Y, 0 as Result   union all
  select 2,100,10,0,0   union all
  select 3,100,20,0,0   union all
  select 4,100,0,50,0   union all
  select 5,100,60,0,0   union all
  select 1,1000,0,100,0   union all
  select 2,1000,100,0,0   union all
  select 3,1000,200,0,0   union all
  select 4,1000,0,500,0 
)
select 
    subid, 
    a, 
    x, 
    y, 
    a+x-y
    +ISNULL((select sum(x) from cte c2 where c2.a=c1.a and c2.subid&lt;c1.subid),0)
    -ISNULL((select sum(y) from cte c2 where c2.a=c1.a and c2.subid&lt;c1.subid),0)
        as Result
from cte c1
order by a,subid


output:

subid       a           x           y           Result
----------- ----------- ----------- ----------- -----------
1           100         0           10          90
2           100         10          0           100
3           100         20          0           120
4           100         0           50          70
5           100         60          0           130
1           1000        0           100         900
2           1000        100         0           1000
3           1000        200         0           1200
4           1000        0           500         700