首页 > 解决方案 > 在条件上用零替换列中的 NULL 值

问题描述

我是 SQL Server 数据库和查询的新手。

我有一个带有 DateTime 和 Current 的 SQL Server 数据库表。当前可能有 NULL 值。

仅当上一条或下一条记录具有某些值时,我才想用零替换当前列中的 NULL 值。提供按升序排序的日期时间。

请帮我写一个 SQL 查询或存储过程和 SQL 查询的组合。

还可以帮助我使用 DateTime 按升序对现有表进行排序。DateTime 不是一个正在运行的系列。

样品表

标签: sqlsql-server-2017-express

解决方案


您可以使用可更新的 CTE 和窗口函数:

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);

如果您只想在select查询中增加一列(而不是更改数据),那么:

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;

推荐阅读