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

前端 未结 5 1435
我在风中等你
我在风中等你 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:29

    Maybe something like the code given below.

    Note: Code not tested. Also, this code needs to consider if you need the previous value based on the ID column or any other requirement like that.

    CREATE TABLE Table1 (Date1 VARCHAR(10), ID VARCHAR(10), Class VARCHAR(10), ID2 INT);
    
    INSERT INTO Table1 Values ('11/30/2015', 'ID1', 'ClassName', 1);
    INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 2);
    INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 3);
    INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 4);
    INSERT INTO Table1 Values ('12/31/2015', 'ID1', 'ClassName', 5);
    INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 6);
    INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 7);
    
    CREATE TABLE Table2 (Date1 VARCHAR(10), ID VARCHAR(10), Class VARCHAR(10), ID2 INT);
    
    DECLARE @Date1 VARCAHR(10), @ID1 VARCHAR(10), @Class VARCHAR(10), @ID2 INT;
    DECLARE @TempDate1 VARCAHR(10); --set default if first record is null
    
    DECLARE CURSOR MYCUR FOR
    SELECT Date1, ID1, Class, ID2
    FROM Table1;
    OPEN MYCUR
    FETCH NEXT FROM MYCUR INTO @Date1, @ID1, @Class, @ID2
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
    
        IF (@Date1 IS NOT NULL)
        BEGIN
            @TempDate1=@Date1
        END
    
        INSERT INTO Table2 VALUES(@TempDate1, @ID1, @Class, @ID2)
    
        FETCH NEXT FROM MYCUR INTO @Date1, @ID1, @Class, @ID2
    END
    
    CLOSE MYCUR
    DEALLOCATE MYCUR
    
    SELECT * FROM Table2
    

提交回复
热议问题