I have a Client data table, selected columns of which are shown below:
Row_ID Client_ID Status_ID From_date To_date
1 123456 4
Simple mark all status changes for each client with 1
(column GRP below).
Than add those number using analytic SUM function:
with tab1 as (
select client_id,from_date, status,
nvl(lag(status) over (partition by client_id order by from_date),-1) status_lag,
case when (nvl(lag(status) over (partition by client_id order by from_date),-1) <> status) then
1 end grp
from tst
)
, tab2 as (
select client_id,from_date, status,status_lag, grp,
sum(grp) over (partition by client_id order by from_date) as RANK
from tab1
)
select * from tab2;
gives as expected
CLIENT_ID FROM_DATE STATUS STATUS_LAG GRP RANK
---------- ------------------- ---------- ---------- ---------- ----------
1001 01.10.2015 00:00:00 1 -1 1 1
1001 02.10.2015 00:00:00 1 1 1
1001 03.10.2015 00:00:00 2 1 1 2
1001 04.10.2015 00:00:00 2 2 2
1001 05.10.2015 00:00:00 3 2 1 3
1001 09.10.2015 00:00:00 1 3 1 4
1002 12.10.2015 00:00:00 1 -1 1 1
1002 13.10.2015 00:00:00 3 1 1 2
1002 15.10.2015 00:00:00 3 3 2
my setup
create table tst
(client_id number,
from_date date,
status number);
insert into tst values (1001, to_date('01-10-15','dd-mm-rr'),1);
insert into tst values (1001, to_date('02-10-15','dd-mm-rr'),1);
insert into tst values (1001, to_date('03-10-15','dd-mm-rr'),2);
insert into tst values (1001, to_date('04-10-15','dd-mm-rr'),2);
insert into tst values (1001, to_date('05-10-15','dd-mm-rr'),3);
insert into tst values (1001, to_date('09-10-15','dd-mm-rr'),1);
insert into tst values (1002, to_date('12-10-15','dd-mm-rr'),1);
insert into tst values (1002, to_date('13-10-15','dd-mm-rr'),3);
insert into tst values (1002, to_date('15-10-15','dd-mm-rr'),3);
commit;