We maintain rows in a table with a version number which will determine the current set of accounts for a version. I need to be able to show the changes between the versions - when a row was ADDED, REMOVED or there was NO CHANGE. I can work out ADDED and NO_CHANGE without any problem, but I'm not sure how I can determine that a row has been REMOVED when it no longer exists in the next version.
I have provided an example piece of SQL below:
with w_acct1 as
(select 'A1' acct, 0 vers from dual
union all
select 'A2' acct, 0 vers from dual
union all
select 'A3' acct, 0 vers from dual
union all
select 'A1' acct, 1 vers from dual
union all
select 'A2' acct, 1 vers from dual
union all
select 'A1' acct, 2 vers from dual
union all
select 'A4' acct, 2 vers from dual)
select a.*,
nvl(lead(acct) over (partition by acct order by vers desc),'NULL') ld,
case when lead(acct) over (partition by acct order by vers desc) is null then
'ADDED'
when lead(acct) over (partition by acct order by vers desc) = acct then
'NO_CHANGE'
else
'REMOVED'
end add_remove
from w_acct1 a
order by vers,acct
Which gives me the following result:
ACCT VERS LD ADD_REMOVE
A1 0 NULL NEW
A2 0 NULL NEW
A3 0 NULL NEW
A1 1 A1 NO_CHANGE
A2 1 A2 NO_CHANGE
A1 2 A1 NO_CHANGE
A4 2 NULL NEW
The result I want is:
ACCT VERS LD ADD_REMOVE
A1 0 NULL NEW
A2 0 NULL NEW
A3 0 NULL NEW
A1 1 A1 NO_CHANGE
A2 1 A2 NO_CHANGE
A3 1 NULL REMOVED
A1 2 A1 NO_CHANGE
A2 2 NULL REMOVED
A4 2 NULL NEW
Note the REMOVED rows associated with the version even though they don't exist in the dataset for that version number.
Can this be done with analytic functions or some other cool Oracle feature I'm missing?
Regards
Richard