SQL Server - 如何填充缺失的列值

标签 sql sql-server

我有一组包含 2 列的日级别记录:

  • 发票日期
  • 发票金额

对于少数记录,invoice_amount 的值缺失。

我需要使用以下逻辑填充发票金额为 NULL 的值:

  1. 查找下一个可用的invoice_amount(日期晚于空白值记录日期)

  2. 对于 invoice_amount 仍为空白(invoice_amount future 日期不存在)的记录,查找最近的 invoice_amount(在日期中)在空白起息日之前)

注意:我们连续多天数据集中的 invoice_amount 为空白:

Please see attached problem and solution dataset

最佳答案

使用 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/

相关文章:

php - mysql语法中的mysql错误

javascript - Node.js API 与 express 和 mysql - 仅在设置、等于和类似组合时应用搜索参数

sql-server - 如何找到哪一列对应于约束?

java - 在 hibernate 中如何以编程方式设置事务的隔离级别,或者如何创建两个具有不同隔离级别的事务

sql - 在 SQL 中将元组插入表中时,模式中属性的顺序重要吗?

sql - SQL 中具有多个 group by 子句的 SUM 和 MAX 函数会导致问题

python - 错误 28000 : Login failed for user DOMAIN\\user with pyodbc

sql - SQL Server 2008 中截断/清除表变量

SQL Server 添加索引而不删除表

mysql - 如何通过属性连接两个表