Chcete vše ve druhé tabulce a poté odpovídající řádky nebo novou group0
v první tabulce.
Myslím, že toto je join
logika:
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;
Tato logika je jednodušší s 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);
EDIT:
Upravená otázka se od původní značně liší. To je jednoduché 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;