如何获取所有先前的值?

时间:2018-11-12 13:05:12

标签: sql sql-server sql-server-2014

有人可以帮助我如何在给定图像中实现结果吗?

enter image description here

我有这样的数据。如何用所有以前的日期数据替换所有空值。 和预期的输出将是一样的。

enter image description here

1 个答案:

答案 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;

您也可以摆脱联接,但是使用正确的索引可能会很快。