简体   繁体   中英

SQL Server: future values on column based on distinct rows of the result set

I have this table

在此处输入图片说明

I now want that level1 future values are completed by doing the previous level1 value minus the level2 .

An example:

level1 at 2019-12-11 00:00 = 2359,11 - 7,74 = 2351,37

level1 at 2019-12-11 01:00 = 2351,37 - 7,74 = 2353,63

and so on.

How can I do that?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM