获取最新更改的信息

我有一个包含很多信息的审核表。我需要查找何时和谁对每个项目的特定列进行了最新更改。

我能够执行返回正确结果的查询,但是发现它是一个巨大的混乱。尤其是因为我需要对许多不同的列执行此操作(我可能会用union进行此操作),并将这些值与最新发布的值进行比较。无论如何...有没有比3级选择更好的方法了?

create table Z_AUDIT
(
  v CHAR(1) not null,      -- A value that is part of a project (ex: project manager)
  t DATE not null,         -- Time of change
  w VARCHAR2(10) not null, -- Who did the change
  p VARCHAR2(10)           -- Project
)

INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'a', sysdate, 'bob');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'a', sysdate-1, 'judy');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'a', sysdate-2, 'bob');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'b', sysdate-3, 'judy');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'b', sysdate-4, 'bob');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'a', sysdate-5, 'judy');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'a', sysdate-6, 'bob');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'b', sysdate-7, 'judy');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 1', 'c', sysdate-8, 'bob');

INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 2', 'b', sysdate, 'bob');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 2', 'a', sysdate-1, 'judy');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 2', 'a', sysdate-2, 'bob');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 2', 'b', sysdate-3, 'judy');
INSERT INTO Z_AUDIT (p, v, t, w) VALUES ('project 2', 'c', sysdate-4, 'bob');

 -- Get the latest change from the rank 1
 select p, w, t, current_value, previous_value
   from ( -- Get only the changes with the where clause and get the rank
         select i.p,
                 i.w,
                 i.t,
                 i.current_value,
                 i.previous_value,
                 rank() over(partition by i.p order by i.t desc) r
           from ( -- Get the previous value for each audit record
                  select p,
                          w,
                          t,
                          v as current_value,
                          LAG(v, 1) OVER(partition by p ORDER BY t) as previous_value
                    from Z_AUDIT) i
          where nvl(current_value, 'a') <> nvl(previous_value, 'a'))
  where r = 1;
项目1,bob,5/9/2020 7:08:55 AM,a,b   项目2,鲍勃,5/11/2020 7:12:39 AM,b,a
评论