Leetcode Problem 2388. Change Null Values in a Table to the Previous Value

2388. Change Null Values in a Table to the Previous Value

Leetcode Solutions

Using Recursive Common Table Expression (CTE) to Replace NULLs

Algorithm

  1. Create a CTE (cte1) that selects id, drink, and a row number (rn) for each row in the CoffeeShop table.
  2. Start the recursive part of the CTE with the first row, where rn = 1.
  3. Recursively join cte1 to itself, where the row number of the current row is one greater than the row number of the previous row.
  4. Use the IFNULL function to replace NULL values in the drink column with the drink value from the previous row.
  5. Continue the recursion until all rows have been processed.
  6. Select id and drink from the final recursive CTE to get the desired output.

erDiagram
    CoffeeShop {
        int id PK
        varchar drink
    }

Using Window Functions to Replace NULLs

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...