sql - 使用先前捕获的值更新空数据
问题描述
我有表格“ childdataviewdetail ”,其中包含“ code ”、“ updateon ”和“ height ”字段。
- “代码”代表Child的代码;
- “ Updateon ”是我们测量那个孩子身高的日期(我们通常每月测量一次);
- “身高”是孩子的身高。
我们有大约 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
我得到了预期的结果,但查询需要很长时间才能执行。请提出任何替代方案。
解决方案
使用窗口函数。但是,您似乎想要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
推荐阅读
- javascript - javascript路径中的Wordpress问题
- flutter - 无法将 mobx 集成到简单的颤振应用程序中,该应用程序会在点击时增加计数器
- java - spring security:BadCredendtials 异常未由链处理且未返回 401
- solr - Apache Solr 索引从 4.7 升级到 5.2
- docker - Golang Docker SDK 镜像构建失败并出现 COPY
- javascript - Auth0 实施未填充
- android - 检测无障碍服务中按下的电源按钮
- excel - 如何在 VBA 中使范围动态化
- regular-language - 如果 L 的字符串由 0 组成,仅证明 L* 是正则的
- jquery - 使用jquery同时为td标签和输入标签设置文本和值