简体   繁体   中英

Oralce SQL nested or inner join when you need to compare the same table but different rows with unique ID values

I'm having a trouble writing a query in ORACLE. I have a Table that contains values. for example:

ID  quantity partID 
123   50       10
100   20       10
100   30       11
123   null     8
456   null     100
789   25       123
456   50       9

I want to get all rows that has same ID but quantities to be 50 and null (exact same pairs of 50 and null only). for the given example I would like to get:

ID  quantity partID 
123   50       10
123   null     8
456   50       9
456   null     100

I tried inner join but it doesn't provide the exact output as expected.

You may try :

select ID, quantity, partID
  from tab
 where ID in
(
 select ID
  from tab
 where nvl(quantity,50)=50
 group by ID
 having count(distinct nvl(quantity,0) )>1
);

ID  QUANTITY    PARTID
123    50         10
123   (null)       8
456   (null)     100
456    50          9

SQL Fiddle Demo

PS you may get the same results by commenting out having count(ID)=2 also but for those cases there may not exist one of 50 or null for values of quantity.

You can use exists :

select t.*
from t
where (t.quantity = 50 and
       exists (select 1 from t t2 where t2.id = t.id and t2.partid = t.partid and t2.value is null)
      ) or
      (t.quantity is null and
       exists (select 1 from t t2 where t2.id = t.id and t2.partid = t.partid and t2.value = 50)
      ) ;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM