Oracle SQL - 用以前的已知值替换null

时间:2015-06-04 18:16:01

标签: sql oracle null

我希望将表格列中的空值替换为该列中以前的已知值。我尝试过很多东西,但我似乎无法弄清楚如何去做。如果有人可以提供帮助那就太棒了。提前谢谢!

PROCESSO    DATAM   HOURM TEMP_T1
-------- ---------- ----- -------
508410   2015.03.29  19   36.15
508410   2015.03.30  11   NULL
508410   2015.03.30  14   NULL
508410   2015.03.30  15   35.36
508410   2015.03.30  23   36.52
508410   2015.03.31  11   NULL
508410   2015.04.01  02   37.06

我希望它看起来像这样:

PROCESSO    DATAM   HOURM TEMP_T1
-------- ---------- ----- -------
508410   2015.03.29  19   36.15
508410   2015.03.30  11   36.15
508410   2015.03.30  14   36.15
508410   2015.03.30  15   35.36
508410   2015.03.30  23   36.52
508410   2015.03.31  11   36.52
508410   2015.04.01  02   37.06

1 个答案:

答案 0 :(得分:2)

尝试last_value分析函数:

SELECT "PROCESSO", "DATAM", "HOURM",
       last_value( "TEMP_T1" ignore nulls )
       OVER (order by "DATAM"
             rows between unbounded preceding and current row
       ) as new_temp
FROM table1

演示==> http://sqlfiddle.com/#!4/48207/2

===========编辑===================

如果要更新表,并且没有主键(唯一标识符),可以尝试基于rowid伪列的解决方案
==> http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm):

MERGE INTO table1 t1
USING (
    SELECT rowid rd, "PROCESSO", "DATAM", "HOURM",
           last_value( "TEMP_T1" ignore nulls )
           OVER (order by "DATAM"
                 rows between unbounded preceding and current row
           ) as new_temp
    FROM table1
) x
ON (t1.rowid = x.rd)
WHEN MATCHED THEN UPDATE SET t1."TEMP_T1" = x.new_temp
;

演示==> http://sqlfiddle.com/#!4/5a9a61/1

但是,您必须确保在运行更新时没有其他进程从该表中删除和插入行,因为当从表中删除行时,Oracle可以将其rowid分配给另一个新行。