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