Как получить все предыдущие значения? - PullRequest
0 голосов
/ 12 ноября 2018

Может кто-нибудь помочь мне, как добиться результата на данном изображении?

enter image description here

У меня есть такие данные. Как я могу заменить все нули со всеми предыдущими данными даты. И ожидаемый результат будет похож.

enter image description here

1 Ответ

0 голосов
/ 12 ноября 2018

SQL Server не поддерживает параметр IGNORE NULL s в LAG() - это то, что вы действительно хотите.

Один метод использует 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;

Вы также можете избавиться от объединения, но оно, вероятно, быстро с правильным индексом.

...