2015-11-20 50 views
0

我想加入兩個表。如何加入兩個表得到以下結果呢?

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

01/B在第一個表中發生了什麼? –

+0

對不起,先生,我想我有一些錯誤,現在是正確的。 – user3259913

+0

我有問題。 如果列值爲NULL,它無法比擬的列值。 – user3259913

回答

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; 
+0

我想在第二個表中的一切, 1.比賽GROUP0和1組 2.如果比賽 - >添加值該行中, 3.如果不匹配 - >添加新行 – user3259913

相關問題