Search code examples
sqlsql-serverwindow-functions

Last_value with IGNORE NULLS in SQL Server


I have a time series that with null values. I want to be replace each null value with the most recent non-non value. From what I've researched, Oracle SQL can easily accomplish this using Last_value with IGNORE NULLS. Is there a similar way to accomplish this using SQL Server 2016? Otherwise I'm just going to code it using C#, but felt using SQL would be faster, cleaner, and easier.

Sec SCORE
1   Null
2   Null
3   5
4   Null
5   8
6   7
7   Null

Should be replaced with:

Sec SCORE
1   Null
2   Null
3   5
4   5
5   8
6   7
7   7

Solution

  • You can do this with two cumulative operations:

    select t.*,
           coalesce(score, max(score) over (partition by maxid)) as newscore
    from (select t.*,
                 max(case when score is not null then id end) over (order by id) as maxid
          from t
         ) t;
    

    The innermost subquery gets the most recent id where there is a value. The outermost one "spreads" that value to the subsequent rows.

    If you actually want to update the table, you can incorporate this easily into an update. But, Oracle cannot do that (easily), so I'm guessing this is not necessary....