首页 > 解决方案 > 使用先前捕获的值更新空数据

问题描述

我有表格“ childdataviewdetail ”,其中包含“ code ”、“ updateon ”和“ height ”字段。

我们有大约 10000 个孩子。很多时候我们忘记取它们的高度,所以它同样捕获 null。我需要一个查询来使用当天之前获取的最新值更新空值。

我编写了一个运行良好的代码,但它花费的时间太长。我需要知道是否有其他可能的方法可以快速完成。

select
 code,
 updateon,
 iif(height is null, 
    (select top 1 height              
     from childdataviewdetail
     where code = t1.code 
            and updateon<=t1.updateon 
            and height is not null
     order by updateon desc)
    ,height) height
from childdataviewdetail t1
order by code, updateon

我得到了预期的结果,但查询需要很长时间才能执行。请提出任何替代方案。

标签: sqlsql-server

解决方案


使用窗口函数。但是,您似乎想要lag(ignore nulls)SQL Server 不支持的。一种方法是两级窗口函数:

select cdvd.*,  -- whatever columns you want here
       coalesce(height,
                max(height) over (partition by code, grp)
               ) as height
from (select cdvd.*,
             count(height) over (partition by code order by updateon) as grp
      from childdataviewdetail cdvd
     ) cdvd
order by code, updateon;

如果height从不减少,那么您可以使用max()更简单的累积:

select cdvd.*,  -- whatever columns you want here
       coalesce(height,
                max(height) over (partition by code order by updatedon)
               ) as height
from childdataviewdetail cdvd

推荐阅读