从两个选择中找到结果的差异

时间:2019-06-14 07:27:10

标签: sql

我有两个表:

table_1:  
A | B | C  
z | x | 12  
z | c | 13  
z | c | 10  
a | s | 14  
a | d | 11  

table_2:  
A | B | C  
z | c | 10  
z | x | 15  
z | x | 11  
a | d | 14  
a | s | 12  

我要:
-按A和B将表分组
-并找出AB的C的总和的差异。

我从开始:

SELECT A, B, SUM(C) from table_1 GROUP BY A, B;  
SELECT A, B, SUM(C) from table_2 GROUP BY A, B;

但是我不知道如何通过添加相等的附加列来加入它们  到table_1.sum(C)-table_2.sum(c)

预期结果如下:

A | B | sum1 | sum2 | diff  
z | x | 12   | 26   | -14 
z | c | 23   | 10   | 13
a | s | 14   | 12   | 2
a | d | 11   | 14   | -3

2 个答案:

答案 0 :(得分:1)

与子查询一起使用连接

select X.A,X.B, sum1, sum2, sum1-sum2 as diff from 
(
SELECT A, B, SUM(C) sum1
from table_1 GROUP BY A, B  
)X inner join
(
SELECT A, B, SUM(C) sum2
from table_2 GROUP BY A, B
)Y on X.A=Y.A and X.B=Y.B

答案 1 :(得分:0)

当两个表中的组不同时,您想做什么? inner join可能很危险,因为群组会消失。

如果要保留所有组,则一种方法是union all / group by

select a, b, sum(c1) as sum1, sum(c2) as sum2,
       (sum(c2) - sum(c1)) as diff
from ((select a, b, c as c1, 0 as c2
       from table_1
      ) union all
      (select a, b, 0 as c1, c as c2
       from table_2
      )
     ) t
group by a, b