SQL Server - 如何填写缺少的列值

时间:2018-04-04 03:06:49

标签: sql sql-server

我在日级别有两列记录:

  • Invoice_date
  • INVOICE_AMOUNT

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

我需要使用以下逻辑填充invoice_amount值为NULL:

  1. 寻找下一个可用的invoice_amount(在空白值记录日期之后的日期)

  2. 对于invoice_amount仍然空白(invoice_amount未来日期不存在)的记录,请查找以前的大多数invoice_amount(在空白值日期之前的日期)

  3. 注意:我们连续多天在数据集中invoice_amount为空:

    Please see attached problem and solution dataset

3 个答案:

答案 0 :(得分:2)

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

这会更新您的表格。如果您需要一个选择查询,可以轻松修改它

答案 1 :(得分:1)

效率不高但似乎有效。尝试:

update test set invoice_amount =   
       coalesce ((select top 1 next.invoice_amount from test next 
                   where next.invoiceDate > test.invoiceDate and next.invoice_amount is not null
                   order by next.invoiceDate),
                (select top 1 prev.invoice_amount from test prev 
                   where prev.invoiceDate < test.invoiceDate and prev.invoice_amount is not null
                   order by prev.invoiceDate desc))
where invoice_amount is null;

答案 2 :(得分:0)

根据给定的示例,您可以将窗口函数self join

一起使用
update t set t.amount = tt.NewAmount 
from table t
inner join (
    select Dates, coalesce(min(amount) over (order by dates desc ROWS BETWEEN 1 PRECEDING AND CURRENT ROW),
                           min(amount) over (order by dates asc ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)) NewAmount
    from table t
) tt on tt.dates = t.dates
where t.amount is null