Translate Excel business logic to T-SQL
select *, ROW_NUMBER() over (order by datum) as rw
into #temp
from #ResultsTable
order by datum
select a.datum, a.window, a.countersout, a.countersin, countersout-countersin as result, rw
into #temp1 from #temp a
select a.datum, a.window, a.countersOUT, a.countersIN,
case when isnull(b.result,0) + a.countersOUT - a.countersIN < 0 then a.countersIN
else (case when (isnull(b.result,0) +a.result) + a.countersOUT - a.countersIN > isnull(c.countersIN,0) + isnull(d.countersIN,0) then isnull(c.countersIN,0) + isnull(d.countersIN,0) + a.countersIN - (isnull(b.result,0) +a.result)
else a.countersOUT end)
end as Result, a.result + b.RESULT as A88
from #temp1 a left join #temp b
on a.rw =b.rw + 1
left join #temp c
on a.rw + 2 = c.rw
left join #temp d
on a.rw + 3 = d.rw
order by a.datum
I have copied your logic as is. But your logic stops making sense after line 12. If you can explain how that makes sense, I will edit this to give you what you want or you can tweak it yourself.