你可以用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;
伊茨克奔甘寫道:一個關於這個問題的博客:http://sqlmag.com/sql-server/how-previous-and-next-condition。 Unfortunatley SQL Server不支持'LAST_VALUE'中的'IGNORE NULLS'選項,那很簡單:'LAST_VALUE(B IGNORE NULLS)OVER(ORDER BY IDX)'。 – dnoeth