【问题标题】:SQL Hadoop - Combine two tables and sumSQL Hadoop - 组合两个表并求和
【发布时间】:2021-05-19 20:17:47
【问题描述】:

我的目标是合并两张表,其中一些 ID 可能出现在一张表中,而另一张表中没有。如果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

我打算先 UNION ALL 这两个表:

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

【问题讨论】:

  • Hadoop 是一个文件系统。你用的是什么数据库?
  • 抱歉,谢谢。我正在使用 DbVisualizer。

标签: sql hadoop dbvisualizer


【解决方案1】:

您可以使用子查询:

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

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2018-07-31
    相关资源
    最近更新 更多