How can I fill the null values with the values up these nulls

后端 未结 2 1187
抹茶落季
抹茶落季 2021-01-26 13:29

How can I fill the null values with the values below these null values?

Example, I have a table like this:

Mat   Name
123   Jerry
Null  Mary
Null  Sam
45         


        
相关标签:
2条回答
  • 2021-01-26 13:47

    I think you mean

    select name, max(value) OVER(ORDER BY name ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) as value
    
    0 讨论(0)
  • 2021-01-26 13:55

    If you are able to add an ID column to your table (if you don't have one already) this query should work

    declare @tbl as table (
        id int
        ,mat int
        ,name varchar(15)
    )
    
    insert into @tbl values (1,123, 'Jerry')
    insert into @tbl values (2,NULL, 'Marry')
    insert into @tbl values (3,NULL, 'Sam')
    insert into @tbl values (4,456, 'Matt')
    insert into @tbl values (5,NULL, 'Harry')
    insert into @tbl values (6,NULL, 'Jin')
    
    SELECT
        id
        ,CASE WHEN
            mat IS NULL THEN
                (SELECT TOP 1 mat FROM @tbl WHERE id<T.id AND mat IS NOT NULL ORDER BY id DESC)
            ELSE mat
        END AS mat
        ,name
    FROM @tbl T
    
    0 讨论(0)
提交回复
热议问题