外部加入或特殊联盟

时间:2013-06-13 17:39:17

标签: sql sql-server union

我这里有一种特殊的联盟实现,假设R1联合R2,表R都可以分成2部分,RA部分是联合的内容和RP部分只是一个数字。

所以我的特殊联盟是R1.A正常联合R2.A,另外如果两个R1上都存在A,则计算新的数字P为1-(1-R1.P)(1-R2.P) ,R2。或者,如果A不在R2或R2.P中,如果A不在R1中,则此数字仅为R1.P。

听起来可能很复杂,但请看一下这个插图: enter image description here

我正在使用MS SQL server 2012,欢迎任何方法,非常感谢

1 个答案:

答案 0 :(得分:3)

您可以使用full outer joinunion 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

实际上,现在我把查询写出来了,我知道为什么我更喜欢连接。当没有聚合时,算术运算更容易表达。