如何使用JOIN的Mysql SUM

时间:2018-01-25 20:28:58

标签: mysql sql sum inner-join

我有以下表格:

purchase_tbl

id | productId | purchaseQuantity 
---+-----------+-----------------
1  | 1         | 30
2  | 2         | 30
3  | 1         | 10
4  | 2         | 10

sale_tbl

id | productId | saleQuantity
---+-----------+-------------
1  | 1         | 10
2  | 2         | 10
3  | 1         | 10
4  | 2         | 10
5  | 1         | 10
6  | 2         | 10

我需要得到这个输出:

productId | totalPurchasedQuantity| totalSaleQuantity
----------+-----------------------+------------------
1         | 40                    | 30
2         | 40                    | 30

我正在使用此查询以及如何获得所需的结果?

SELECT purchase_tbl.productId
    , SUM(purchase_tbl.purchaseQuantity) AS totalPurchaseQuantity
    , SUM(sale_tbl.saleQuantity) AS totalSaleQuantity
FROM purchase_tbl
JOIN sale_tbl
    ON purchase_tbl.productId = sale_tbl.productId
GROUP BY purchase_tbl.productId

当前输出

productId | totalPurchaseQuantity | totalSaleQuantity
----------+-----------------------+------------------
1         | 120                   | 60
2         | 120                   | 60

2 个答案:

答案 0 :(得分:2)

您最好在单独的查询中进行分组,因为表中每个产品都有多条记录,这些记录会产生交叉产品。

SELECT purchase.productId, totalPurchaseQuantity, totalSaleQuantity
FROM
(SELECT purchase_tbl.productId
    , SUM(purchase_tbl.purchaseQuantity) AS totalPurchaseQuantity
FROM purchase_tbl
GROUP BY purchase_tbl.productId) purchase
INNER JOIN
(SELECT sale_tbl.productId
    , SUM(sale_tbl.saleQuantity) AS totalSaleQuantity
FROM sale_tbl
GROUP BY sale_tbl.productId
) sale ON sale.productId= purchase.productId;

答案 1 :(得分:0)

要获得预期结果,您必须在加入单个表之前对其进行聚合。您的查询如下:

SELECT A.productId, A.totalpurchaseQuantity, B.totalsaleQuantity
FROM
(SELECT productId, SUM(purchaseQuantity) 
   totalpurchaseQuantity FROM purchase_tbl 
    GROUP BY productId) A JOIN 
(SELECT productId, SUM(saleQuantity) 
   totalsaleQuantity FROM sale_tbl 
    GROUP BY productId) B ON
A.productId=B.productId;