我正在使用Oracle SQL.
我有下表:
Timestamp | A | B
13-11-14 06.49.54.004 | 50 | 70
13-11-14 06.49.54.005 | NULL| 80
13-11-14 06.49.54.006 | NULL| NULL
13-11-14 06.49.54.007 | 40 | 70
13-11-14 06.49.54.008 | 20 | 90
13-11-14 06.49.54.009 | 30 | NULL
Run Code Online (Sandbox Code Playgroud)
如何将NULL值替换为每列的最后一个值?这是预期的输出表:
Timestamp | A | B
13-11-14 06.49.54.004 | 50 | 70
13-11-14 06.49.54.005 | 50 | 80
13-11-14 06.49.54.006 | 50 | 80
13-11-14 06.49.54.007 | 40 | 70
13-11-14 06.49.54.008 | 20 | 90
13-11-14 06.49.54.009 | 30 | 90
Run Code Online (Sandbox Code Playgroud)
请指教.
您可以将first_value()分析函数与windowing子句一起使用,使用timestamp列进行排序并忽略空值:
select timestamp, a, b,
first_value(a) ignore nulls over (order by timestamp desc
rows between current row and unbounded following) as new_a,
first_value(b) ignore nulls over (order by timestamp desc
rows between current row and unbounded following) as new_b
from table_name
order by timestamp;
TIMESTAMP A B NEW_A NEW_B
---------------------------- ---------- ---------- ---------- ----------
13-NOV-14 06.49.54.004000000 50 70 50 70
13-NOV-14 06.49.54.005000000 80 50 80
13-NOV-14 06.49.54.006000000 50 80
13-NOV-14 06.49.54.007000000 40 70 40 70
13-NOV-14 06.49.54.008000000 20 90 20 90
13-NOV-14 06.49.54.009000000 30 30 90
Run Code Online (Sandbox Code Playgroud)
或者使用last_value()改为:
select timestamp, a, b,
last_value(a) ignore nulls over (order by timestamp
rows between unbounded preceding and current row) as new_a,
last_value(b) ignore nulls over (order by timestamp
rows between unbounded preceding and current row) as new_b
from table_name
order by timestamp;
Run Code Online (Sandbox Code Playgroud)
该窗口包含当前行,因此如果该值不为null,则将使用该值; 否则它将使用第一个/最后一个非空值(因为该ignore null子句),因为它以指定的顺序遍历窗口.