[英]DB2 Get latest modified and previous value from audit table
I have a audit table, i am trying to get the current and previous value for a column(rank) with audit timestamp information.我有一个审计表,我正在尝试使用审计时间戳信息获取列(排名)的当前值和先前值。 I would like to get the timestamp when the value was changed.我想获取值更改时的时间戳。 Eg:例如:
For id = 1
, rank was latest changed from 3 to 5
on 13-05-2021 14:10
by userid = 2
.对于id = 1
,排名最近在 2021 年 5 月13-05-2021 14:10
由userid = 2
from 3 to 5
更改为 5。 I have written below query it gives the current and previous modified value but it gives the latest date
and userid ( 17-05-2021 20:00
and 2
), because row_number is ordered by timestamp.我在下面写了查询,它给出了当前和以前的修改值,但它给出了latest date
和用户 ID( 17-05-2021 20:00
和2
),因为 row_number 是按时间戳排序的。
with v_rank as (
select * from (
select
id,
a.rank as current_rank,
b.rank as previous_rank,
a.log_timestamp,
a.log_username,
row_number() over(partition by a.id order by a.log_timestamp) as rnum
from
user a
inner join user b on a.id = b.id and a.log_timestamp > b.timestamp
where
a.rank != b.rank
order by a.log_timestamp, b.timestamp
) where rnum = 1
)
select * from v_rank
Any suggestion on how can i get the correct timestamp(13-05-2021 14:10)
and userid(2)
.关于如何获得正确timestamp(13-05-2021 14:10)
和userid(2)
的任何建议。 Edit: Rank can also be null, in that case i need to get the blank in query result.编辑:排名也可以是 null,在这种情况下我需要在查询结果中得到空白。
Expected output:预期 output:
You seem to want lag()
with filtering:你似乎想要lag()
过滤:
select u.*
from (select u.*,
lag(rank) over (partition by id order by log_timestamp) as prev_rank
from user u
) u
where rank <> prev_rank;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.