来自 2 个表的不同值与来自相同两个表的总和相结合

Distict values from 2 tables combined with aggregating sums from the same two tables

我想执行以下操作:

参见下面的示例:

Table答:

  1. 姓名=Al,年龄=20,工资=10
  2. 姓名=Al,年龄=20,工资=20
  3. 姓名=鲍勃,年龄=22,薪水=25

Table B

  1. 姓名=Al,年龄=20,工资=30
  2. 姓名=Al,年龄=20,工资=40
  3. 姓名=鲍勃,年龄=22,薪水=35

预期输出:

  1. 姓名=Al,年龄=20,工资A=30,工资B=70,差额=-40
  2. 姓名=Bob,年龄=22,工资A=25,工资B=35,差额=-10

如何在 SQL 中写这个?我使用 Teradata。

您可以只 group by 并使用 union all 合并表 A 和表 B 的查询结果。

 select name, age, max(salaryA), max(salaryB), max(salaryA) - max(salaryB) as difference
 from (
 select name, age, sum(salary) as salaryA, null as salaryB
 from tablea 
 group by name, age
 union all
 select name, age, null as salaryA, sum(salary) as salaryB
 from tableb 
 group by name, age) t
 group by name, age
 SELECT A.name, A.age, A.SalaryA, B.SalaryB, A.SalaryA - B.SalaryB as difference
 FROM (
      SELECT name, age, SUM(Salary) as SalaryA
      FROM TableA
      GROUP BY name, age
      ) as A
INNER JOIN 
      (
      SELECT name, age, SUM(Salary) as SalaryB
      FROM TableB
      GROUP BY name, age 
      ) as B
 ON A.name = B.name
AND A.age  = B.age