MySQL查询导致不同表中{2}列的总和减去

时间:2016-01-16 21:58:54

标签: mysql sql

我有一个MySQL DB,包含以下表格:

产品

Product_ID | Product_Name
     1     |     Blaster
     2     |     Faser
     3     |     BFG

订单

Order_ID | Product_ID | Order_Product_Qnt
    1    |     1      |        10
    2    |     2      |        5
    3    |     3      |        7
    4    |     2      |        10

塞尔斯

Sell_ID | Product_ID | Sel_Product_Qnt
    1   |      2     |        5
    2   |      1     |        1
    3   |      3     |        2

我想要做的是一个查询,其中列出了所有产品及其金额。

结果应为:

Product_Name | Quantity
BFG          |    5
Blaster      |    9
Faser        |    10

按照Barnar的建议,我得到了这段代码:

SELECT 
    Products.Product_Name,
    COALESCE (SUM(Orders.Order_Product_Qnt), 0) - COALESCE (SUM(Sells.Sells_Product_Qnt), 0) AS Quantity
FROM 
    Products
LEFT JOIN 
    Orders ON Products.Product_ID = Orders.Product_ID
LEFT JOIN 
    Sells ON Products.Product_ID = Sells.Product_ID
GROUP BY 
    Products.Product_Name

查询有效,但返回错误的值。

例如,我有一个产品有6个订单,1个卖出,逻辑指示6-1 = 5,但该查询给我4个结果。

或另一个有18个订单和6个卖出的订单,返回60个(应该是12个)。

任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:0)

也许是这样的?

SELECT 
product_name,
orders_cnt - sales_cnt AS Quantity
FROM (
    SELECT product_name,
    SUM(orders) AS orders_cnt,
    SUM(sales) AS sales_cnt
    FROM (
        SELECT products.product_name,
        ifnull(orders.order_product_qnt, 0) orders,
        ifnull(sells.sells_product_qnt,0) sales
    FROM products
    LEFT JOIN orders ON products.product_id = orders.product_id
    LEFT JOIN sells ON products.product_id = sells.product_id
    ) t1
GROUP BY product_name ) t2

答案 1 :(得分:0)

终于搞定了,忘了在这里发布我的解决方案:

    SELECT
        Products.Product_ID,
        Products.Product_Name,
        IFNULL(b.SB - c.SC, 0) AS Quantity,
   FROM Produtos_Table
        LEFT JOIN (
            SELECT 
                Product_ID,
                SUM(Quantity) AS SB
            FROM
                Orders 
            GROUP BY Product_ID
        ) b 
        ON Products.Product_ID = b.Product_ID
        LEFT JOIN (
            SELECT
                Product_ID,
                SUM(Sell_Product_Qnt) AS SC 
            FROM 
                Sells
            GROUP BY 
                Product_ID
        ) c
        ON Products.Product_ID = c.Product_ID
   GROUP BY
        Products.Product_Name