[英]SQL DB2 Toad - Sum from two tables by ID
I was hoping to find the sum from two tables with columns ID and Amount, grouping by ID.我希望从两个包含 ID 和 Amount 列的表中找到总和,按 ID 分组。 My first attempt was to UNION the two tables first and then conduct a sum and group by, but I was hoping to know of a better way.
我的第一次尝试是先联合两个表,然后进行求和和分组,但我希望知道更好的方法。
Inputs:输入:
Table 1表格1
ID Amount
123 100
123 100
145 500
167 600
Table 2
ID Amount
123 100
123 100
145 500
199 600
Output输出
ID Amount
123 400
145 1000
167 600
199 600
You can do:你可以做:
select id, sum(amount) as amount
from (
select id, amount from table_1
union all
select id, amount from table_2
) x
group by id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.