You want the last value of level1
and then the cumulative values of level2
.
If I assume that level1
is non-increasing, then one method is:
select t.*,
min(level1) over () - sum(level2) over (order by date) as new_value
from t;
If you need to actually find the previous non-null value of level1
, you can also do that. Here is a method using window functions:
select t.*,
(max(level1) over (partition by last_level1_date) -
sum(level2) over (order by date)
) as new_value
from (select t.*,
max(case when level1 is not null then date end) over (order by date) as last_level1_date
from t
) t;
Oh, this would be simpler if SQL Server supported IGNORE NULL
s on LAG()
and/or LAST_VALUE()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.