简体   繁体   中英

Outer Join Or special Union

I have a special kind of Union to implement here, suppose R1 union R2, both table R can be split into 2 part, RA part which is the content to be union and RP part which is just a number.

So my special union is to R1.A normal union R2.A, in addition calculate a new number P that is 1-(1-R1.P)(1-R2.P) if a A exist on both R1,R2. Or this number is just R1.P if A is not in R2 or R2.P if A is not in R1.

might sounds complicated, but take a look at this illustration: 在此处输入图片说明

I am using MS SQL server 2012, welcome any approach, many thanks

You can do this with either a full outer join or a union all . Personally, I prefer the 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;

My bias in favor of joins is simply that I think they are more likely to use indexes for optimization and to optimize well. It is possible that the union all / group by version would work as well:

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

Actually, now that I write the query out, I know why I prefer the join. The arithmetic operations are simpler to express when there is no aggregation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM