您可以使用outer apply
操作员来做到这一点:
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;
无论空值或空“岛”的数量如何,这都会起作用。您可能有值,然后是空值,然后是值,又是空值。它仍然可以工作。
但是,如果假设(在您的问题中)成立:
一旦我有了NULL
, 就NULL
到最后了 - 所以我想用最新的值填充它。
有一个更有效的解决方案。我们只需要找到最新的(按 排序时idx
)值。修改上述查询,where id <= t.id
从子查询中删除:
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;