[英]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. 我在用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). 我想获取所有具有相同ID但数量为50和null(完全相同的50和null的对)的行。 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
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. PS您也可以通过注释掉
having count(ID)=2
来获得相同的结果,但是对于那些情况,数量值可能不存在50
或为null
。
You can use exists
: 您可以使用
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)
) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.