-
Notifications
You must be signed in to change notification settings - Fork 2
/
2388.sql
95 lines (86 loc) · 2.08 KB
/
2388.sql
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
-- [ LeetCode ] 2388. Change Null Values in a Table to the Previous Value
SELECT
id,
IFNULL(drink, SubTable_drink) AS drink
FROM (
SELECT
WithRowNum.id,
WithRowNum.drink,
MAX(SubTable.row_num) AS latest_one,
SubTable.drink AS SubTable_drink
FROM (
SELECT
ROW_NUMBER() OVER() AS row_num,
id,
drink
FROM CoffeeShop
) AS WithRowNum
LEFT JOIN (
SELECT
ROW_NUMBER() OVER() AS row_num,
id,
drink
FROM CoffeeShop
) AS SubTable
ON (
WithRowNum.drink IS NULL
AND
WithRowNum.row_num > SubTable.row_num
AND
SubTable.drink IS NOT NULL
)
GROUP BY WithRowNum.id
) AS Result;
-- 아래와 같이 WITH 구를 사용하여 임시 테이블을 생성해 반복되는 서브쿼리에 대한 최적화가 가능하다.
WITH WithRowNum (row_num, id, drink) AS (
SELECT
ROW_NUMBER() OVER() AS row_num,
id,
drink
FROM CoffeeShop
)
SELECT
id,
IFNULL(drink, SubTable_drink) AS drink
FROM (
SELECT
WithRowNum.id,
WithRowNum.drink,
MAX(SubTable.row_num) AS latest_one,
SubTable.drink AS SubTable_drink
FROM WithRowNum
LEFT JOIN WithRowNum AS SubTable
ON (
WithRowNum.drink IS NULL
AND
WithRowNum.row_num > SubTable.row_num
AND
SubTable.drink IS NOT NULL
)
GROUP BY WithRowNum.id
) AS Result;
-- 최종적으로 WITH RECURSIVE 구를 활용해 최적화가 가능하다.
WITH RECURSIVE WithRowNum (row_num, id, drink) AS (
SELECT
ROW_NUMBER() OVER() AS row_num,
id,
drink
FROM CoffeeShop
), Result (row_num, id, drink) AS (
SELECT
row_num,
id,
drink
FROM WithRowNum
WHERE row_num = 1
UNION ALL
SELECT
WithRowNum.row_num,
WithRowNum.id,
IFNULL(WithRowNum.drink, Result.drink) AS drink
FROM Result
JOIN WithRowNum
ON Result.row_num = WithRowNum.row_num - 1
)
SELECT id, drink
FROM Result;