sqlsql-servert-sqlrow

Auto fill field with value from above row value


I would like to auto fill empty values with the above value.

Query

SELECT 
      Nr,
      [Name]
FROM #TEMP

Table:

enter image description here

I want my output to look like this:

enter image description here

Thanks.


Solution

  • One way to achieve that is to use subquery:

    SELECT t1.Nr, Name = (SELECT TOP 1 Name 
                          FROM #temp t2 
                          WHERE Name IS NOT NULL 
                            AND t1.Nr >= t2.Nr
                          ORDER BY Nr DESC)
    FROM #temp t1
    ORDER BY Nr;
    

    LiveDemo

    or CROSS APPLY:

    SELECT t1.Nr, sub.Name
    FROM #temp t1
    CROSS APPLY (SELECT TOP 1 Name 
                 FROM #temp t2 
                 WHERE Name IS NOT NULL 
                   AND t1.Nr >= t2.Nr
                 ORDER BY Nr DESC) AS sub
    ORDER BY Nr;
    

    LiveDemo2