如何减去来自 SQL 中不同表的值?

how to substract values that come from different tables in SQL?

我有两个 table:

 
Table 1
+--------+--------+
|  name  | amount |
+--------+--------+
| Thomas |     35 |
| Robert |     20 |
| Peter  |     15 |
| Josh   |     100|
+--------+--------+


Table 2
+--------+--------+
|  name  | amount |
+--------+--------+
| Thomas |      5 |
| Robert |      5 |
| Peter  |     10 |
| Josh   |     15 |
+--------+--------+

我想从另一列的另一行中减去一列中的一行,在不同的 table 中。每个 table 上的行数相同,我想从第一行(来自 Table 2)中减去第一行(来自 Table 1),依此类推。

所以我最终会得到

 
Table 3
+--------+--------+
|  name  | amount |
+--------+--------+
| Thomas |     30 |
| Robert |     15 |
| Peter  |      5 |
| Josh   |     85 |
+--------+--------+
 

我已经尝试了几个小时如何进行推导,但无济于事。

对于这样的一对一关系,只需join:

select name, t1.amount - t2.amount as amount
from table1 t1
inner join table2 t2 using(name)

为了使其正常工作,names 在两个表中应该是唯一的。

UNION ALL table。否定 table2 金额。 GROUP BY 结果:

select name, sum(amount)
from
(
  select name, amount from table1
  union all
  select name, - amount from table2
) dt
group by name

还将处理仅在 table 之一或 table 中多次出现的名称。