-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathreplace_null_value_with_value_previous_value.sql
More file actions
52 lines (43 loc) · 1.31 KB
/
replace_null_value_with_value_previous_value.sql
File metadata and controls
52 lines (43 loc) · 1.31 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
+------------+----------+
| mysequence | mynumber |
+------------+----------+
| 1 | 3 |
| 2 | NULL |
| 3 | 5 |
| 4 | NULL |
| 5 | NULL |
| 6 | 2 |
+------------+----------+
Result:
+------------+----------+------------+
| mysequence | ORIGINAL | CALCULATED |
+------------+----------+------------+
| 1 | 3 | 3 |
| 2 | NULL | 3 |
| 3 | 5 | 5 |
| 4 | NULL | 5 |
| 5 | NULL | 5 |
| 6 | 2 | 2 |
+------------+----------+------------+
# Replace NULL value in a row with a value from the previous known value
/*CREATE TABLE test(mysequence INT, mynumber INT);
INSERT INTO test VALUES(1, 3);
INSERT INTO test VALUES(2, NULL);
INSERT INTO test VALUES(3, 5);
INSERT INTO test VALUES(4, NULL);
INSERT INTO test VALUES(5, NULL);
INSERT INTO test VALUES(6, 2);
*/
select * from test;
with cte_step1 as (
select mysequence
, mynumber
, sum(case when mynumber is NULL then 0 else 1 end)
over (order by mysequence) as val
from test
)
select mysequence
, mynumber
, first_value(mynumber)
over (partition by val order by mysequence) as res
from cte_step1