【问题标题】:Filling in null values with the values from the most recent data - SQL用最新数据中的值填充空值 - SQL
【发布时间】:2020-10-20 16:07:09
【问题描述】:

对于上表,使用最新的先前数据(即 10 月 16 日的数据)填充空值的合理 SQL 服务器解决方案是什么?

非常感谢

【问题讨论】:

    标签: sql sql-server null


    【解决方案1】:

    一种方法使用cross apply

    select t.date, coalesce(t.value, t2.value), coalesce(t.value2, t2.value2)
    from t cross apply
         (select top (1) t2.*
          from t t2
          where t2.value is not null and t2.date < t.date
          order by t2.date desc
         ) t2;
        
    

    如果未填充的值仅针对最近的行,那么效率更高:

    select t.date, coalesce(t.value, t2.value), coalesce(t.value2, t2.value2)
    from t cross join
         (select top (1) t2.*
          from t t2
          where t2.value is not null
          order by t2.date desc
         ) t2;
    

    如果您想更新值,那么相关子查询可能是最简单的:

    更新 设置值 = (选择顶部 (1) t2.value 从 t t2 其中 t2.value 不为空并且 t2.date

    【讨论】:

      【解决方案2】:

      使用子查询:

       SELECT Date
      ,ISNULL(Value, (SELECT TOP 1 Value From Temp T1 WHERE T.Date > T1.DATE AND T1.Value is not null)) AS Value 
      ,ISNULL(Value2, (SELECT TOP 1 Value2 From Temp T1 WHERE T.Date > T1.DATE AND T1.Value2 is not null))  AS Value2
      FROM Temp AS T
      ORDER BY DATE DESC
      

      【讨论】:

      • 另一个人回答了 cross apply 这就是为什么我添加了另一种方式。
      猜你喜欢
      • 1970-01-01
      • 2020-07-14
      • 2019-11-30
      • 2022-12-03
      • 2020-11-29
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多