我已经执行了完整的外部联接,我得到以下内容:
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)