我是SQL Server数据库和查询的新手。
我有一个带有DateTime和Current的SQL Server数据库表。当前可能具有NULL值。
仅当上一条或下一条记录具有某个值时,我才想用零替换Current列中的NULL值。提供的DateTime以升序排序。
请帮助我编写一个SQL查询或存储过程和SQL查询的组合。
还可以帮助我用DateTime升序对现有表进行排序。 DateTime不是正在运行的系列。
答案 0 :(得分:0)
您可以使用可更新的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;