Oracle从审计表中获取旧值和新值

时间:2018-05-15 16:00:37

标签: sql oracle

假设我有一个像这样(简化)的审计表结构。

OID,VALUE,CHANGED_DATE

我想要做的是编写一个查询,对于每个VALUE更改,它会给我以下输出。

OLD_VALUE,NEW_VALUE,CHANGED_DATE

我该怎么做呢?所以,例如,如果我有

OID|VALUE|CHANGED_DATE
----------------------
1  |ABC  |15-JAN-18
2  |DEF  |22-JUN-18
3  |XYZ  |16-JUL-18

我希望看到输出:

OLD_VALUE|NEW_VALUE|CHANGED_DATE
--------------------------------
ABC      |DEF      |22-JUN-18
DEF      |XYZ      |16-JUL-18

2 个答案:

答案 0 :(得分:1)

使用lag()

select oid, lag(oid) over (order by changed_date) as prev_oid, changed_date
from t;

此代码包含所有三行。如果你想消除第一个:

select *
from (select oid, lag(oid) over (order by changed_date) as prev_oid, changed_date
      from t
     ) t
where prev_oid is not null;

答案 1 :(得分:1)

您想要lead()

select t.*
from (select oid, lead(value) over (order by changed_date) as next_value, changed_date
      from table 
     ) t
where next_value is not null;