我有一组包含 2 列的日级别记录:
- 发票日期
- 发票金额
对于少数记录,invoice_amount 的值缺失。
我需要使用以下逻辑填充发票金额为 NULL 的值:
查找下一个可用的
invoice_amount
(日期晚于空白值记录日期)对于
invoice_amount
仍为空白(invoice_amount
future 日期不存在)的记录,查找最近的invoice_amount
(在日期中)在空白起息日之前)
注意:我们连续多天数据集中的 invoice_amount
为空白:
最佳答案
使用 CROSS APPLY 查找下一个和上一个非空发票金额
update p
set Invoice_Amount = coalesce(nx.Invoice_Amount, pr.Invoice_Amount)
from Problem p
outer apply -- Next non null value
(
select top 1 *
from Problem x
where x.Invoice_Amount is not null
and x.Invoice_Date > p.Invoice_Date
order by Invoice_Date
) nx
outer apply -- Prev non null value
(
select top 1 *
from Problem x
where x.Invoice_Amount is not null
and x.Invoice_Date < p.Invoice_Date
order by Invoice_Date desc
) pr
where p.Invoice_Amount is null
这会更新您的表格。如果需要选择查询,可以轻松修改
关于SQL Server - 如何填充缺失的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49642085/