在条件下用零替换列中的 NULL 值
Replace NULL Values in a column with Zeros on a condition
我是 SQL 服务器数据库和查询的新手。
我有一个 SQL 服务器数据库 table,带有 DateTime 和 Current。当前可能有 NULL 值。
我想仅当前一个或下一个记录具有某些值时才用零替换当前列中的 NULL 值。提供的日期时间按升序排序。
请帮我写一个SQL查询或存储过程和SQL查询的组合。
还帮我把现有的 table 和 DateTime 按升序排列。 DateTime 不是 运行 系列。
您可以使用可更新的 CTE 和 window 函数:
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;
我是 SQL 服务器数据库和查询的新手。
我有一个 SQL 服务器数据库 table,带有 DateTime 和 Current。当前可能有 NULL 值。
我想仅当前一个或下一个记录具有某些值时才用零替换当前列中的 NULL 值。提供的日期时间按升序排序。
请帮我写一个SQL查询或存储过程和SQL查询的组合。
还帮我把现有的 table 和 DateTime 按升序排列。 DateTime 不是 运行 系列。
您可以使用可更新的 CTE 和 window 函数:
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;