You can do this using the outer apply statement:
select t.id, t1.colA, t2.colB, t3.colC from table t outer apply(select top 1 colA from table where id <= t.id and colA is not null order by id desc) t1 outer apply(select top 1 colB from table where id <= t.id and colB is not null order by id desc) t2 outer apply(select top 1 colC from table where id <= t.id and colC is not null order by id desc) t3;
This will work regardless of the number of zeros or zero islands. You can have values, then zeros, then values ββagain, zeros again. It will work anyway.
If, however, there is an assumption (in your question):
As soon as I have NULL , NULL all to the end - so I want to fill it with the last value.
there is a more effective solution. We only need to find the latter (when ordering with idx values). By changing the above query, removing where id <= t.id from the subqueries:
select t.id, colA = coalesce(t.colA, t1.colA), colB = coalesce(t.colB, t2.colB), colC = coalesce(t.colC, t3.colC) from table t outer apply (select top 1 colA from table where colA is not null order by id desc) t1 outer apply (select top 1 colB from table where colB is not null order by id desc) t2 outer apply (select top 1 colC from table where colC is not null order by id desc) t3;
source share