Change Null Values in a Table to the Previous Value Problem
#2388
Description
LeetCode Problem 2388.
Table: CoffeeShop
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| drink | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row in this table shows the order id and the name of the drink ordered. Some drink rows are nulls.
Write a solution to replace the null values of the drink with the name of the drink of the previous row that is not null. It is guaranteed that the drink on the first row of the table is not null.
Return the result table in the same order as the input.
The result format is shown in the following example.
Example 1:
Input:
CoffeeShop table:
+----+-------------------+
| id | drink |
+----+-------------------+
| 9 | Rum and Coke |
| 6 | null |
| 7 | null |
| 3 | St Germain Spritz |
| 1 | Orange Margarita |
| 2 | null |
+----+-------------------+
Output:
+----+-------------------+
| id | drink |
+----+-------------------+
| 9 | Rum and Coke |
| 6 | Rum and Coke |
| 7 | Rum and Coke |
| 3 | St Germain Spritz |
| 1 | Orange Margarita |
| 2 | Orange Margarita |
+----+-------------------+
Explanation:
For ID 6, the previous value that is not null is from ID 9. We replace the null with "Rum and Coke".
For ID 7, the previous value that is not null is from ID 9. We replace the null with "Rum and Coke;.
For ID 2, the previous value that is not null is from ID 1. We replace the null with "Orange Margarita".
Note that the rows in the output are the same as in the input.
Solution
Approach: Group each null with the last non-null row above it
A NULL drink must take the value of the closest non-null row before it, in the table's row order. Window functions can do this without session variables:
- Number the rows with
ROW_NUMBER() OVER ()to freeze the input order. COUNT(drink) OVER (ORDER BY rn)counts only non-null values, so it goes up by 1 on every non-null row and stays flat on null rows. Each non-null row and the nulls after it therefore share one group number.- Inside a group the only non-null value is the first row's drink, so
MAX(drink)over the group returns it for every row of that group. - Finally sort by the row number to return the rows in input order.
The statement guarantees the first row is not null, so every null has a group that starts with a real value.
In Pandas this is just a forward fill, ffill().
WITH numbered AS (
SELECT id, drink, ROW_NUMBER() OVER () AS rn
FROM CoffeeShop
), grouped AS (
SELECT id, drink, rn,
COUNT(drink) OVER (ORDER BY rn) AS grp -- +1 at every non-null drink
FROM numbered
)
SELECT id,
MAX(drink) OVER (PARTITION BY grp) AS drink
FROM grouped
ORDER BY rn;