SQL: How to fill empty cells with previous row value?

前端 未结 5 2231
深忆病人
深忆病人 2020-12-08 22:35

I need to produce the column \"required\" in the following table using SQL without using loops and correlated sub queries. Is this possible in SQL 2008?

Date         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 23:04

    This is the "Last non-null puzzle," and here's one of several elegant solutions:

    If your "sparse" table is SparseTable with columns Date, Customer, Value then:

    with C as
    (select *,
        max(case when Value is not null then [Date] end)
            over (partition by Customer order by [Date] rows unbounded preceding) as grp
     from SparseTable
    )
    insert into FullTable
    select *, 
        max(Value) over (partition by Customer, grp order by [Date] rows unbounded preceding) as Required
    from C
    

    Where Value couldn't be filled forward it will still be NULL, so you can then

    update FullTable set Required = 0 where Required is null
    

提交回复
热议问题