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

SQL Server-如何填写缺少的列值,sql,sql-server,Sql,Sql Server,我有一组日间记录,共有两列: 发票日期 发票金额 对于少数记录,缺少发票金额的值 我需要使用以下逻辑填写为空的发票金额值: 在空白值记录日期后面的日期中查找下一个可用的发票金额 发票金额为空白的发票,金额不存在于未来日期,在空白值日期< /P>之前查找最前的发票金额 注:数据集中发票金额为空的连续多天: 效率不高,但似乎有效。尝试: update test set invoice_amount = coalesce ((select top 1 next.invoice_am

我有一组日间记录,共有两列:

发票日期 发票金额 对于少数记录,缺少发票金额的值

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

在空白值记录日期

后面的日期中查找下一个可用的发票金额

发票金额为空白的发票,金额不存在于未来日期,在空白值日期< /P>之前查找最前的发票金额 注:数据集中发票金额为空的连续多天:


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

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;

使用交叉应用查找下一个和上一个非空发票金额

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

这将更新回您的表。如果您需要一个select查询,可以很容易地修改它。

根据给定的示例,您可以使用带有自联接的窗口函数


您使用的是什么版本的SQL Server?嘿,Squirrel,我使用的是SQL Server 2014,所以类似于COALESCEInvoice\u金额、LEADInvoice\u按发票日期的订单金额、LAGInvoice\u按发票日期的订单金额?感谢您的见解。可能存在连续3-4天的发票金额缺失的情况。我在想那该怎么办?
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