来自两个表的计算

时间:2017-09-30 19:24:50

标签: mysql join sum

我有两张桌子。一个表包含带代码和初始数量的表

表T1:

+-------------+------------+
| Code        | QTY        |
+-------------+------------+
| a           | 1          |
+-------------+------------+
| a           | 1          |
+-------------+------------+
| a           | 1          |
+-------------+------------+
| b           | 1          |
+-------------+------------+
| c           | 5          |
+-------------+------------+

第二个表T2包含代码和多少件

表T2:

+-------------+------------+
|Code         | qty        | 
+-------------+------------+
| a           | 1          |              
+-------------+------------+
| c           | 2          |                
+-------------+------------+

现在我需要使用当前的qunatities进行输出,可用的代码数量和输出应如下所示:

输出:

+-------------+------------+
| Code        | QTY        |
+-------------+------------+
| a           | 2          |
+-------------+------------+
| b           | 1          |
+-------------+------------+
| c           | 3          |
+-------------+------------+

我曾试过这个:

SELECT t1.code, (SUM(t1.qunatity) - SUM(t2.qunatity)) AS Avilable
FROM  table t1
LEFT JOIN table2 t2 ON t2.code = t1.code
GROUP BY t1.code

我得到的输出是:

输出:

+-------------+------------+
| Code        | Available  |
+-------------+------------+
| a           | 0          |
+-------------+------------+
| b           | null       |
+-------------+------------+
| c           | 2          |
+-------------+------------+

哪个不正确,我应该得到a = 2,b = 0.在这种情况下只有c是正确的。我做错了什么?

3 个答案:

答案 0 :(得分:2)

尝试在聚合结果上使用连接以避免行之间的关系产生

select  tt11.code, (tt1.t1_quantity - tt2.t2_quantity) AS Available
FROM  (
 select  t1.code, SUM(t1.quantity) as t1_quantity
    FROM  table t1
    group by t1.code
    )  tt1 
left join (
    select  t2.code, SUM(t2.quantity) as t2_quantity
    FROM  table t2
    group by t2.code
    ) tt2 on tt2.code = tt1.code 

答案 1 :(得分:2)

您可以尝试以下解决方案:

SELECT t1.code, (IFNULL(t1.qty, 0) - IFNULL(t2.qty, 0)) AS 'Available' FROM (
    SELECT code, SUM(qty) AS qty FROM table1 GROUP BY code
)t1 LEFT JOIN (   
    SELECT code, SUM(qty) AS qty FROM table2 GROUP BY code
)t2 ON t1.code = t2.code;
  

演示: http://sqlfiddle.com/#!9/7b124/1/0

SELECT只有数量大于0的代码,您可以使用以下查询:

SELECT t1.code, (IFNULL(t1.qty, 0) - IFNULL(t2.qty, 0)) AS 'Available' FROM (
    SELECT code, SUM(qty) AS qty FROM table1 GROUP BY code
)t1 LEFT JOIN (   
    SELECT code, SUM(qty) AS qty FROM table2 GROUP BY code
)t2 ON t1.code = t2.code
WHERE (IFNULL(t1.qty, 0) - IFNULL(t2.qty, 0)) > 0;
  

演示: http://sqlfiddle.com/#!9/7b124/1/1

答案 2 :(得分:2)

SELECT tt.code, sum(tt.qq)
FROM (
    SELECT code, sum(qty) as qq
    FROM tbl_1
    GROUP BY code
    UNION
    SELECT code, sum(-qty) as qq
    FROM tbl_2
    GROUP BY code) as tt
GROUP BY code

DEMO