0

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

所以我的特殊联合是R1.A普通联合R2.A,另外计算一个新的数字P,即1-(1-R1.P)(1-R2.P),如果A在R1,R2上都存在。或者如果 A 不在 R2 中,这个数字就是 R1.P,如果 A 不在 R1 中,这个数字就是 R2.P。

可能听起来很复杂,但看看这个插图: 在此处输入图像描述

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

4

1 回答 1

3

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

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

于 2013-06-13T17:43:11.853 回答