根据sql server中可用于immidieate先前日期的数据填写当前行

时间:2018-05-23 10:17:17

标签: sql sql-server

我在下面给出了数据:

Table

在上述结构中,我们需要推进没有评级值的直接先前评级(库存3)行。最终数据应该是这样的:

Final result

任何人都可以帮助sql查询吗?

2 个答案:

答案 0 :(得分:0)

只需使用lag()

select date, action,
       coalesce(rating, lag(rating) over (order by date)) as rating,
       outcome
from t;

您可以使用可更新的CTE将其合并到更新中:

with toupdate as (
      select date, action,
             coalesce(rating, lag(rating) over (order by date)) as as new_rating,
             outcome
      from t
     )
update toupdate
    set rating = new_rating;

答案 1 :(得分:0)

您可以在遇到null值时使用运行总和来计算组,并使用max填充每个组的值。

select date,action,rating,outlook,max(rating) over(partition by grp) as new_rating
from (select t.*
      ,sum(case when rating is null then 0 else 1 end) over(order by date) as grp
      from tbl t
     ) t