答案 0 :(得分:1)
SQL Server不支持IGNORE NULL
中的LAG()
s选项,这是您真正想要的。
一种方法使用OUTER APPLY
:
select . . .,
coalesce(t.col1, t2.col1) as col1,
coalesce(t.col2, t2.col2) as col2,
coalesce(t.col3, t2.col3) as col3,
coalesce(t.col4, t2.col4) as col4,
coalesce(t.col5, t2.col5) as col5,
coalesce(t.col6, t2.col6) as col6
from t outer apply
(select top (1) t2.*
from t t2
where t2.col7 < t.col7 and
t2.col1 is not null
order by t2.col7 desc
) t2;
这是在SQL Server 2012+中运行的更快的方法:
select . . .,
coalesce(t.col1, t2.col1) as col1,
coalesce(t.col2, t2.col2) as col2,
coalesce(t.col3, t2.col3) as col3,
coalesce(t.col4, t2.col4) as col4,
coalesce(t.col5, t2.col5) as col5,
coalesce(t.col6, t2.col6) as col6
from (select t.*,
max(case when t.col1 is not null then t.col7 end) over (order by t.col7) as max_non_null_col7
from t
) t left join
t t2
on t2.col7 = t.max_non_null_col7;
您也可以摆脱联接,但是使用正确的索引可能会很快。