SQL: Accumulative columns & Sum Across the Row

后端 未结 2 1270
无人共我
无人共我 2021-01-29 08:38

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          


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 09:08

    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;
    

提交回复
热议问题