1

I am new to SQL Server databases and queries.

I have a SQL Server database table with DateTime and Current. Current may have NULL values.

I want to replace NULL values in Current column with zeros only when either previous or next record has some value. Provided DateTime sorted in Ascending order.

Please help me to write a SQL query or a combination of stored procedure and SQL query.

Also help me to sort the existing table with DateTime in Ascending order. DateTime is not a running series.

Sample Table

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • **Partial answer:** There's a method called `coalesce` which will turn NULLs into any value of your choice. `coalesce(Current, 0)`. This won't help check the next or previous rows for you though. For that I have no idea. – Dan Feb 07 '19 at 17:39
  • Show what you have tried as a [mcve]. –  Feb 07 '19 at 18:29

1 Answers1

0

You can use updatable CTEs and window functions:

with toupdate as (
      select t.*, lag(current) over (order by datetime) as prev_current,
             lead(current) over (order by datetime) as next_current
      from t
     ) 
update toupdate
    set current = 0
    where current is null and (prev_current is not null or next_current is not null);

If you just want an additional column in a select query (as opposed to changing the data), then:

with t as (
      select t.*, lag(current) over (order by datetime) as prev_current,
             lead(current) over (order by datetime) as next_current
      from t
     ) 
select t.*,
       (case when current is null and (prev_current is not null or next_current is not null)
             then 0 else current
        end) as new_current
from t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786