user3384231
user3384231

Reputation: 4053

SQL Join on the same table

Table T
P_ID | Name | Status
1      ABC    Ordered
1      ABC    Processing
1      ABC    Imported
2      PQR    Ordered
2      PQR    Failed
3      LMN    Ordered

Expected Result

Table T
P_ID | Name | Status
2      PQR    Ordered
2      PQR    Failed 
3      LMN    Ordered

I am not getting the correct result with the following query. I want to find all the records that have status Ordered but do not have the status "Imported".

select c1.P_ID,c1.Name,c2.Status
from T c1, T c2
where c1.P_ID = c2.P_ID
c1.Status="Ordered" and c2.status != "Imported"

Using Oracle 11g database

Upvotes: 0

Views: 45

Answers (2)

Luuk
Luuk

Reputation: 14948

select c1.P_ID, c1.Name, c1.Status
from T c1
where c1.Status = 'Ordered' and 
      NOT EXISTS (SELECT 1
                  FROM T c2
                  WHERE c1.P_ID = c2.P_ID and c2.status = 'Imported'
                 );

Upvotes: 3

Goran Kutlaca
Goran Kutlaca

Reputation: 2024

You can use the following code:

select c1.P_ID,c1.Name,c1.Status
  from T c1
 where exists (select 1
                 from T
                where P_ID = c1.P_ID
                  and Status="Ordered"
                  and rownum = 1)
   and not exists (select 1
                     from T
                    where P_ID = c1.P_ID
                      and Status="Imported"
                      and rownum = 1)

Upvotes: 2

Related Questions