来自 2 个表的不同值与来自相同两个表的总和相结合
Distict values from 2 tables combined with aggregating sums from the same two tables
我想执行以下操作:
- 从 table A 和 B 获取不同的姓名和年龄。
- 然后我想从table A 和table B 中计算每组姓名和年龄的薪水。我希望输出显示:Name, Age, (sum Table A), (sum Table B), (sum Table A- sum Table B)
参见下面的示例:
Table答:
- 姓名=Al,年龄=20,工资=10
- 姓名=Al,年龄=20,工资=20
- 姓名=鲍勃,年龄=22,薪水=25
Table B
- 姓名=Al,年龄=20,工资=30
- 姓名=Al,年龄=20,工资=40
- 姓名=鲍勃,年龄=22,薪水=35
预期输出:
- 姓名=Al,年龄=20,工资A=30,工资B=70,差额=-40
- 姓名=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
我想执行以下操作:
- 从 table A 和 B 获取不同的姓名和年龄。
- 然后我想从table A 和table B 中计算每组姓名和年龄的薪水。我希望输出显示:Name, Age, (sum Table A), (sum Table B), (sum Table A- sum Table B)
参见下面的示例:
Table答:
- 姓名=Al,年龄=20,工资=10
- 姓名=Al,年龄=20,工资=20
- 姓名=鲍勃,年龄=22,薪水=25
Table B
- 姓名=Al,年龄=20,工资=30
- 姓名=Al,年龄=20,工资=40
- 姓名=鲍勃,年龄=22,薪水=35
预期输出:
- 姓名=Al,年龄=20,工资A=30,工资B=70,差额=-40
- 姓名=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