Replace null value with previous available value in Row SQL server query

前端 未结 5 1518
我在风中等你
我在风中等你 2021-01-06 15:02

I am looking for building a query to replace null value with previous available values.can somebody help.Here is the table currently looking like

11/30/2015          


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 15:30

    This question is a bit old, but you can achieve the same thing using the first_row function with SQL Server (starting with 2012 version)

    First, you can create a new column that contains an increasing number for each "block" of a non-null date and all the next null values:

    WITH CTE AS
    (
        SELECT *,
               SUM(CASE WHEN Date1 is NULL then 0 else 1 END) AS block
        FROM your_table
    )
    

    This CTE will create something like this (I'm using the column names of Shakeer's answer):

    Date1          ID   Class      ID2    block
    11/30/2015     ID1  ClassName   1      1
    NULL           ID1  ClassName   2      1
    NULL           ID1  ClassName   3      1
    NULL           ID1  ClassName   4      1
    12/31/2015     ID1  ClassName   5      2
    NULL           ID1  ClassName   6      2
    NULL           ID1  ClassName   7      2
    

    Now, you can use the first_row function to get the first value of each "block":

    SELECT *,
            first_row(Date1) OVER (PARTITION BY block ORDER BY ID2) AS NewDate
    FROM CTE
    

    I hope this helps.

提交回复
热议问题