首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将列中的空值替换为条件中的零

问将列中的空值替换为条件中的零
EN

Stack Overflow用户
提问于 2019-02-08 01:07:58
回答 1查看 226关注 0票数 1

我不熟悉SQL Server数据库和查询。

我有一个包含DateTime和Current的SQL Server数据库表。Current可能具有空值。

仅当前一条记录或下一条记录中有一些值时,我才希望将当前列中的空值替换为零。提供的DateTime按升序排序。

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

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

​

​

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-08 01:10:46

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

代码语言:javascript
复制
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查询中增加一列(而不是更改数据),那么:

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54578651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档