I have below one table which contains id
which can be multiple along with multiple p_id
and status
. But I need to fetch only the latest record based on the status
column.
For e.g
id = 1
For this id we have p_id
as A1, A1, A2 out of which A1 latest status is completed but A2 is still in Initiated. So, the output for id
1 should Initiated.
Similarly for id = 2
we have to fetch "unsuccessful" record.
In short for each id
if there are any p_id
which is not completed then we need to show the latest output.
create table test(id number, p_id varchar2(50), status varchar2(50));
insert into test values(1,'A1','Initiated');
insert into test values(1,'A2','Initiated');
insert into test values(1,'A1','Completed');
insert into test values(2,'A1','Initiated');
insert into test values(2,'A2','Initiated');
insert into test values(2,'A2','Unsuccessful');
insert into test values(2,'A1','Completed');
My Query-
select id,p_id,status from(
select id,p_id,status,
rank() over(partition by id)rnk from test order by id
) where rnk = 1;
DB Version: OracleLive
expected output -
+----+------+--------------+
| Id | P_Id | Status |
+----+------+--------------+
| 1 | A2 | Initiated |
| 2 | A2 | Unsuccessful |
+----+------+--------------+
I need to check if any of the p_id
is completed
if yes then need to fetch only initiated
row. And if p_id
is completed and other p_id
is in unsuccessful status then need to print unsuccessful because for that p_id
there are no initiated record irrespective of timestamp I need to fetch the desired result based on "Initiated" value