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
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.