If "/>
I have the below table:
Can you please help me how to get results for the below scenarios dynamically?
If I supply Emp = 1 and HeaderID = 123 and Status = Failed, it should return the results as follows:
If I supply Emp =1 and HeaderID = 111 and status = Failed, it should return the results as follows:
Thanks in advance, please.
I think you need one more column, such as time or extra id or amount, for ordering as you displayed the data. To provide this criteria I added a time column( time
) to your data as in the below demonstration :
with t(empid,headerid,status,time) as
(
select 1,123,'Failed' , '2019-06-22 17:00:00' from dual union all
select 1,321,'Pending', '2019-06-22 17:10:00' from dual union all
select 1,555,'Pending', '2019-06-22 17:20:00' from dual union all
select 1,111,'Failed' , '2019-06-22 17:30:00' from dual union all
select 1,222,'Pending', '2019-06-22 17:40:00' from dual union all
select 2,333,'Failed' , '2019-06-22 17:50:00' from dual union all
select 2,444,'Pending', '2019-06-22 18:00:00' from dual union all
select 3,555,'Failed' , '2019-06-22 18:10:00' from dual
), t2 as
(
select sum(case when status = 'Failed' then 1 else 0 end)
over (partition by empid order by time) as rn,
t.*
from t
)
select *
from t2
where (rn, empid) in
( select rn, empid
from t2
where empid = &i_empid -- 1
and headerid = &i_headerid -- 123
and status = 'Failed' )
order by time;
you can substitute 1
& 123
or 1
& 111
or 2
& 333
or 3
& 555
respectively, as you wish.
Edit ( due to your comment ) :
If you want to return the first row with Pending
status just after the one with Failed
status you can try to use :
with t(empid,headerid,status,time) as
(
select 1,123,'Failed' , '2019-06-22 17:00:00' from dual union all
select 1,321,'Pending', '2019-06-22 17:10:00' from dual union all
select 1,555,'Pending', '2019-06-22 17:20:00' from dual union all
select 1,111,'Failed' , '2019-06-22 17:30:00' from dual union all
select 1,222,'Pending', '2019-06-22 17:40:00' from dual union all
select 2,333,'Failed' , '2019-06-22 17:50:00' from dual union all
select 2,444,'Pending', '2019-06-22 18:00:00' from dual union all
select 3,555,'Failed' , '2019-06-22 18:10:00' from dual
), t2 as
(
select sum(case when status = 'Failed' then 1 else 0 end)
over (partition by empid order by time) as rn,
t.*
from t
), t3 as
(
select t2.*,
row_number() over (partition by empid,rn,status order by time) as rn2
from t2
)
select *
from t3
where (rn,rn2, empid) in
( select rn,rn2, empid
from t3
where empid = 1--&i_empid
and headerid = 123 -- &i_headerid
and status = 'Failed'
)
and status = 'Pending';
again you can substitute the same values used in the above query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.