[英]how to substract values that come from different tables in SQL?
我有两个表:
Table 1 +--------+--------+ | name | amount | +--------+--------+ | Thomas | 35 | | Robert | 20 | | Peter | 15 | | Josh | 100| +--------+--------+ Table 2 +--------+--------+ | name | amount | +--------+--------+ | Thomas | 5 | | Robert | 5 | | Peter | 10 | | Josh | 15 | +--------+--------+
我想从另一个表中的另一列的另一行中减去一列中的一行。 每个表上的行数相同,我想从第一行(来自表 2)中减去第一行(来自表 1),依此类推。
所以我最终会得到
Table 3 +--------+--------+ | name | amount | +--------+--------+ | Thomas | 30 | | Robert | 15 | | Peter | 5 | | Josh | 85 | +--------+--------+
我已经尝试了几个小时如何进行扣除无济于事。
对于这样的 1-1 关系,只需join
:
select name, t1.amount - t2.amount as amount
from table1 t1
inner join table2 t2 using(name)
为了使其正常工作, name
在两个表中都应该是唯一的。
UNION ALL
的表。 否定 table2 金额。 按结果GROUP BY
:
select name, sum(amount)
from
(
select name, amount from table1
union all
select name, - amount from table2
) dt
group by name
还将处理仅在一个表中找到的名称,或在一个表中多次找到的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.