Welcome to Subscribe On Youtube
2388. Change Null Values in a Table to the Previous Value
Description
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.
Solutions
Solution 1: SQL Query
We can use a temporary variable $cur$ to record the previous value that is not $null$. If the current value is $null$, then assign the value of $cur$ to the current value, otherwise we update the value of $cur$ to the current value.
Solution 2
We first use the window function row_number() to generate a sequence number for each row, and then use the sum() window function to generate a grouping sequence number. The generation rule of the grouping sequence number is: if the value of the current row is $null$, the grouping sequence number is the same as the previous row, otherwise the grouping sequence number is increased by one. Finally we use the max() window function to get the only value in each group that is not $null$.
-
# Write your MySQL query statement below SELECT id, CASE WHEN drink IS NOT NULL THEN @cur := drink ELSE @cur END AS drink FROM CoffeeShop; -- Solution 2 # Write your MySQL query statement below WITH S AS ( SELECT *, ROW_NUMBER() OVER () AS rk FROM CoffeeShop ), T AS ( SELECT *, SUM( CASE WHEN drink IS NULL THEN 0 ELSE 1 END ) OVER (ORDER BY rk) AS gid FROM S ) SELECT id, MAX(drink) OVER ( PARTITION BY gid ORDER BY rk ) AS drink FROM T;