I have a table and its record:
Profile | Level | CHgt | BHgt | SHgt | Z ABCD1 | 1 | 15 | 11 | 50 | 0 ABCD1 | 2 | 15 | 11 | 70 | 0 ABCD1 | 3
This would be easier in more recent versions of SQL Server. But you can do this using apply
:
select t.*, t2.Bhgt2,
(case when level = 0 then 0 else SHgt2 end) as Shgt2,
(CHgt + t2.Bhgt2 + (case when level = 0 then 0 else SHgt2 end) ) as Z
from t cross apply
(select sum(Bhgt) as Bhgt2,
sum(SHgt) as SHgt2
from t t2
where t2.profile = t.profile and t2.level <= t.level
) t2;