需要在MySQL中连接三个表并从两个表中减去总重复值

时间:2014-10-13 02:40:54

标签: mysql

所以我有这三个表:

表1:业务

+----------+----------+
| ID       | customer |
+----------+----------+
|    A     | NY       | 
|    B     | NJ       |
|    C     | CT       |
+----------+----------+

表2:2014

+----------+----------+
| business | cost     |
+----------+----------+
|    A     | 10000    | 
|    A     | 5000     | 
|    B     | 3000     |
|    C     | 5000     |
+----------+----------+

表3:2013

+----------+----------+
| business | cost     |
+----------+----------+
|    A     | 15000    | 
|    A     | 5000     | 
|    B     | 10000    |
|    C     | 2000     |
+----------+----------+

我希望得到以下结果:

+----------+----------+
| ID       | diff     |
+----------+----------+
|    A     | -5000    | 
|    B     | -7000    |
|    C     | 3000     |
+----------+----------+

本质上,我正在尝试构建一个查询,该查询使用第一个表中的业务名称来标识要在第二个和第三个表中求和和减去的值。

这是我正在尝试的,但它返回了错误的值:

SELECT ID, sum(2014.cost)-sum(2013.cost) as diff
FROM business 
JOIN 2014 ON business.ID = 2014.business 
JOIN 2013 ON business.ID = 2013.business 
GROUP BY ID;

1 个答案:

答案 0 :(得分:1)

你的联接正在为一些列添加不必要的数字,你需要调整你的sql以获得正确的结果;

SELECT ID, 
       (SELECT SUM(cost) FROM 2014 WHERE business = ID)
        -(SELECT SUM(cost) FROM 2013 WHERE business = ID) AS diff
FROM business 
GROUP BY ID;