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;
Two items: 1) Gordon's response was virtually spot on except for the Level=0. Should be Level=1
2) I'm not convinced the last row of your desired results is correct, I think you are off by 10. If I am not correct, let me know and I will re-visit this.
Declare @Table table (Profile varchar(25),Level int,CHgt int,BHgt int, SHgt int, Z int)
Insert into @Table values
('ABCD1' , 1 , 15 , 11 , 50 , 0),
('ABCD1' , 2 , 15 , 11 , 70 , 0),
('ABCD1' , 3 , 15 , 11 , 70 , 0),
('ABCD2' , 1 , 15 , 11 , 60 , 0),
('ABCD2' , 2 , 15 , 11 , 80 , 0),
('ABCD2' , 3 , 15 , 11 , 80 , 0),
('ABCD3' , 1 , 15 , 11 , 40 , 0),
('ABCD3' , 2 , 15 , 11 , 60 , 0),
('ABCD3' , 3 , 15 , 11 , 60 , 0)
select A.Profile
,A.Level
,A.CHgt
,A.BHgt
,A.SHgt
,B.Bhgt2
,Shgt2 = case when Level = 1 then 0 else SHgt2 end
,Z = CHgt + B.Bhgt2 + case when level = 1 then 0 else SHgt2 end
From @Table A
Cross Apply (Select Bhgt2 = sum(Bhgt)
,SHgt2 = sum(SHgt)
From @Table B
Where B.Profile = A.Profile and A.Level >= B.Level
) B;
Returns
Profile Level CHgt BHgt SHgt Bhgt2 Shgt2 Z
ABCD1 1 15 11 50 11 0 26
ABCD1 2 15 11 70 22 120 157
ABCD1 3 15 11 70 33 190 238
ABCD2 1 15 11 60 11 0 26
ABCD2 2 15 11 80 22 140 177
ABCD2 3 15 11 80 33 220 268
ABCD3 1 15 11 40 11 0 26
ABCD3 2 15 11 60 22 100 137
ABCD3 3 15 11 60 33 160 208