请帮我查询ms-access
我必须前往表格:
Table A:
Prim_key For_key Total
1 ID1 10
2 ID1 20
3 ID2 30
4 ID2 10
Table B:
Prim_key For_key Total
1 ID1 20
2 ID1 5
3 ID2 20
4 ID2 10
我需要选择并显示表A和B中的For_key和Sum总计字段并减去总和,如下所示
For Key Total_A Total_B Substract
ID1 30 25 5
ID2 40 30 10
Sory因为我的英语不好。 谢谢你的帮助
答案 0 :(得分:1)
您可以使用带有UNION ALL
的子查询来确保您还获得仅存在于两个表之一中的ID值:
SELECT For_key,
SUM(TotalA) AS Total_A,
SUM(TotalB) AS Total_B,
SUM(TotalA)-SUM(TotalB) AS Subtract
FROM (
SELECT For_key, Total AS TotalA, 0 AS TotalB
FROM A
UNION ALL
SELECT For_key, 0, Total
FROM B
) AS C
GROUP BY For_key