As you know the LAG() & LEAD() analytic functions access data from a previous and next row in the same result set without the use of a self-join. But is it possible to i
Oracle 11 supports the option ignore nulls
which does exactly what you want. Of course, your question is about SQL Server, but sometimes it is heartening to know that the functionality does exist somewhere.
It is possible to simulate this functionality. The idea is to assign null values to a group, based on the preceding value. In essence, this is counting the number of non-null values before it. You can do this with a correlated subquery. Or, more interestingly, with the difference of two row numbers. Then within the group, you can just use max()
.
I think the following does what you want. Assume that col
contains NULL
values and ordering
has the ordering for the rows:
select t.*,
max(col) over (partition by grp) as LagOnNull
from (select t.*,
(row_number() over (order by ordering) -
row_number() over (partition by col order by ordering)
) as grp
from table t
) t;
The lead()
is similar but the ordering is reversed. And, this will work with additional partitioning keys, but you need to add them to all the window expressions.