SQL Hadoop - 合并两个表并求和

SQL Hadoop - Combine two tables and sum

我的目标是合并两个 table,其中一些 ID 可能出现在一个 table 而不是另一个。如果ID和年份相同,则金额相加。

Table 1:
ID   Year  Amount
111  2010  10.50
111  2011  5
123  2010  6
124  2010  8

Table 2:
ID  Year  Amount
111 2010  10
124 2011  10
125 2011  5

Output:
ID   Year  Amount
111  2010  20.50
111  2011  5
123  2010  6
124  2010  8
124  2011  10
125  2011  5

我本来打算首先将两个 table 全部联合起来:

select *
from schema.table1
UNION ALL
select *
from schema.table2

但这让我离我的目标只有一点点。我应该做 case when 语句吗,我可以做一个 UNION ALL 和一个 sum 吗?

select ID, year, sum(a.year + b.year)
from schema.table1 a
UNION ALL
from schema.table2 b

您可以使用子查询:

select id, year, sum(amount)
from ((select *
       from schema.table1
      ) union all
      (select *
       from schema.table2
      )
     ) t12
group by id, year;

您也可以使用 full join,但使用 coalesce() 的日志:

select coalesce(t1.id, t2.id), coalesce(t1.year, t2.year),
       (coalesce(t1.amount, 0) + coalesce(t2.amount, 0))
from schema.table1 t1 full join
     schema.table2 t2
     on t1.id = t2.id and t1.year = t2.year;