簡體   English   中英

Oracle查詢消除不考慮Null的重復項

[英]Oracle query eliminate duplicates not considering Null

我執行了完整的外部聯接,得到以下信息:

ColumnFromTable1          ColumnFromTable2
     AAA                       ABA
     AAA                       Null          <-  remove
     AAA                       ACC
     BBB                       Null
     CCC                       CDC
     Null                      EFE
     DDD                       FFF
     Null                      FFF           <-  remove
     GGG                       FFF

我真正想要的是壓縮行以除去重復項,這樣我的結果將是:

ColumnFromTable1          ColumnFromTable2
     AAA                       ABA
     AAA                       ACC
     BBB                       Null
     CCC                       CDC
     Null                      EFE
     DDD                       FFF
     GGG                       FFF

基本上我需要消除

AAA  Null
Null  FFF

因為我的AAA或FFF都為非空值。 但是我需要保持

BBB  Null
Null  EFE

因為沒有BBB或EFE非零

我嘗試修改我的完整外部聯接(如果需要可以將其發布),還嘗試將這些結果包裝在子查詢中。

在這里編輯是為此帖子簡化的查詢

select ColumnFromTable1, ColumnFromTable2 from Table1 t1
       full outer join Table2 t2 on t1.common_code = t2.common_code 
       group by ColumnFromTable1, ColumnFromTable2 

row_number()看起來很有希望:

select c1, c2
  from (
    select c1, c2, 
           row_number() over (partition by c1 order by c2) r1,
           row_number() over (partition by c2 order by c1) r2
      from t)
  where not ((c1 is null and r2 > 1) or (c2 is null and r1 > 1))

演示

當空值不是按順序排列時,它將消除空值。

將您已經在CTE中計算出的完整外部聯接放入,您可以通過執行以下操作進一步過濾它:

with f (c1, c2) as (
  ... -- full outer join you already computed here
)
a (x) as ( -- repeated c1 with non-null c2
  select c1
  from f
  group by c1
  having count(c2) > 0
),
b (x) as ( -- repeated c2 with non-null c1
  select c2
  from f
  group by c2
  having count(c1) > 0
)
select *
from f
where not(c1 in (select x from a) and c2 is null)
  and not(c2 in (select x from b) and c1 is null)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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