Sql 使用以前捕获的值更新空数据
我有表childdataviewdetail,其中包含字段代码、更新和高度 代码代表儿童的代码; Updateon是我们测量孩子身高的日期,我们通常每月测量一次; 身高是孩子的身高。 我们有大约10000个孩子。很多时候,我们忘记了测量它们的高度,所以它捕捉到了空值。 我需要一个查询,用当天之前获取的最新值更新null值 我已经写了一个代码,它可以很好地工作,但它需要太长的时间。我需要知道是否有其他可能的方法来快速完成Sql 使用以前捕获的值更新空数据,sql,sql-server,Sql,Sql Server,我有表childdataviewdetail,其中包含字段代码、更新和高度 代码代表儿童的代码; Updateon是我们测量孩子身高的日期,我们通常每月测量一次; 身高是孩子的身高。 我们有大约10000个孩子。很多时候,我们忘记了测量它们的高度,所以它捕捉到了空值。 我需要一个查询,用当天之前获取的最新值更新null值 我已经写了一个代码,它可以很好地工作,但它需要太长的时间。我需要知道是否有其他可能的方法来快速完成 select code, updateon, iif(height i
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
我得到了预期的结果,但执行查询需要很长时间。请建议其他选择。使用窗口功能。但是,您似乎希望忽略空值,而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;
如果高度从未降低,则可以使用累积最大值,这更简单:
select cdvd.*, -- whatever columns you want here
coalesce(height,
max(height) over (partition by code order by updatedon)
) as height
from childdataviewdetail cdvd
所以,您想用该日期最近的非空值替换每个空值吗?我不想在原始表中替换它。我需要一个查询来获得这样的输出