如何连接两个表以获得以下结果?

时间:2015-11-20 02:27:44

标签: sql oracle join

我想加入两张桌子。

TABLE_A

GROUP0     GROUP1     SUM_A
---------------------------
01           A         100         
01           B         200
04           D         700

表-B

GROUP0      GROUP1     SUM_B
---------------------------
01                     300
01           A         350
02           B         400
03           C         500

如何加入表格以获得以下结果?

GROUP0     GROUP1          SUM_A           SUM_B
------------------------------------------------
01                             0            300
01          A                100            350
01          B                200              0
02          B                  0            400
03          C                  0            500
04          D                700              0

1 个答案:

答案 0 :(得分:1)

您想要第二个表中的所有内容,然后匹配第一个表中的行或新group0

我认为这是join逻辑:

select coalesce(t1.group0, t2.group0) as group0, 
       coalesce(t1.group1, t2.group1) as group1,
       t1.sum_a, t2.sum_b
from table1 t1 full outer join
     table2 t2
     on t1.group0 = t2.group0 
where (t2.group0 is not null and (t1.group1 = t2.group1 or t1.group0 is null)) or
      t2.group0 is null;

使用union all

可以更轻松地使用此逻辑
select t2.group0, t2.group1, t1.sum_a, t2.sum_b
from table2 t2 left join
     table1 t1
     on t2.group0 = t1.group0 and t2.group1 = t1.group1
union all
select t1.group1, t1.group1, t1.suma, 0
from table1
where not exists (select 1 from table2 t2 where t2.group0 = t1.group0);

编辑:

修改后的问题与原版完全不同。这是一个简单的full outer join

select coalesce(t1.group0, t2.group0) as group0, 
       coalesce(t1.group1, t2.group1) as group1,
       coalesce(t1.sum_a, 0) as sum_a, coalesce(t2.sum_b, 0) as sum_b
from table1 t1 full outer join
     table2 t2
     on t1.group0 = t2.group0  and t1.group1 = t2.group1;