我如何从审计中获得旧值和新值 table

how do i get old value and new value from audit table

您好,我正在处理审计数据,我在 table 中有以下数据。

colm1  colm2   colm3  

f1      50     4/5/2017 3.38

f1      70     4/5/2017 3.40

f1      80     5/5/2017 3.40

f1      30     5/5/2017 5.40

我想在 table 中显示更改的时间和内容 期望的输出

colm1   oldvalue  newvalue  date 

f1      50         70       4/5/2017

f1      70         80       5/5/2017

f1      80         30       5/5/2017

您可以使用 lag():

select a.colm1, a.colm2 as newvalue,
       lag(colm2) over (partition by colm1 order by colm3) as prevvalue,
       colum3
from audit a;

如果您只需要三行:

select a.*
from (select a.colm1, a.colm2 as newvalue,
             lag(colm2) over (partition by colm1 order by colm3) as prevvalue,
             colum3
      from audit a
     ) a
where prevvalue is not null;
;With cte(colm1 ,colm2,colm3)
AS
(
SELECT 'f1', 50 ,'4/5/2017 3.38'    Union all
SELECT 'f1', 70 ,'4/5/2017 3.40'    Union all
SELECT 'f1', 80 ,'5/5/2017 3.40' Union all
SELECT 'f1', 30 ,'5/5/2017 5.40'
)
SELECT colm1,Val AS OldValue,colm2 AS newvalue,colm3 From
(
SELECT colm1 ,colm2,LAG(colm2)OVER( order by colm3 )Val,LEFT(colm3,8)colm3 from cte 
)dt
WHERE dt.Val iS NOT NULL 

输出

colm1   OldValue    newvalue    colm3
----------------------------------------
f1      50           70         4/5/2017
f1      70           80         5/5/2017
f1      80           30         5/5/2017