您可以使用 afull outer join
或 a来执行此操作union all
。就个人而言,我更喜欢full outer join
:
select coalesce(r1.a, r2.a),
(case when r1.p is null then r2.p
when r2.p is null then r1.p
else 1 - (1-r1.p)*(1-r2.p)
end) as p
from r1 full outer join
r2
on r1.a = r2.a;
我对连接的偏爱只是因为我认为他们更有可能使用索引进行优化并且优化得很好。union all
/版本也可能group by
会起作用:
select a,
(case when count(*) = 1 then coalesce(min(r1p), min(r2p))
else 1 - (1 - min(r1p))*(1 - min(r2p))
end) as p
from (select r1.a, r1.p as r1p, null as r2p
union all
select r2.a, null, r2.p
) t
group by a
实际上,现在我写出了查询,我知道为什么我更喜欢加入。当没有聚合时,算术运算更容易表达。