簡體   English   中英

當需要比較同一表但具有唯一ID值的不同行時,可以使用Oralce SQL嵌套或內部聯接

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

我在用ORACLE編寫查詢時遇到麻煩。 我有一個包含值的表。 例如:

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

我想獲取所有具有相同ID但數量為50和null(完全相同的50和null的對)的行。 對於給定的示例,我想得到:

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

我嘗試了內部聯接,但未提供預期的確切輸出。

您可以嘗試:

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小提琴演示

PS您也可以通過注釋掉having count(ID)=2來獲得相同的結果,但是對於那些情況,數量值可能不存在50或為null

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM