-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2388-ChangeNullValuesInATableToThePreviousValue.sql
More file actions
66 lines (61 loc) · 2.44 KB
/
2388-ChangeNullValuesInATableToThePreviousValue.sql
File metadata and controls
66 lines (61 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
-- 2388. Change Null Values in a Table to the Previous Value
-- 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.
-- Create table If Not Exists CoffeeShop (id int, drink varchar(20))
-- Truncate table CoffeeShop
-- insert into CoffeeShop (id, drink) values ('9', 'Rum and Coke')
-- insert into CoffeeShop (id, drink) values ('6', 'None')
-- insert into CoffeeShop (id, drink) values ('7', 'None')
-- insert into CoffeeShop (id, drink) values ('3', 'St Germain Spritz')
-- insert into CoffeeShop (id, drink) values ('1', 'Orange Margarita')
-- insert into CoffeeShop (id, drink) values ('2', 'None')
-- use value
SELECT
id,
IF(drink IS NULL, @a, @a := drink) AS drink
FROM
CoffeeShop
SELECT
id,
@pre_value := IF(drink IS NOT NULL, drink, @pre_value) AS drink
FROM
CoffeeShop