MySQL查询选择,SUM,LEFT JOIN

时间:2014-12-24 13:54:53

标签: mysql select group-by sum left-join

名为库存的表1包含列商品
名为 Products_sold 的表2包含项目,数量
名为 products_purchased 的表3包含项目,数量

我需要获得三列的sql查询,例如

(产品)(表1中的所有项目)
(已售出产品)(product_sold表中每个项目的数量总和)
(购买的产品)(product_purchased表中每个项目的数量总和)

我有查询,但无法正常使用

  Select stock.Items as Products, 
         SUM(Products_sold.Quantity) as [Products Sold], 
         SUM(Products_purchased.Quantity) as [Products purchased]
  From 
         (
           (Stock LEFT JOIN products_purchased ON stock.Items=products_purchased.Items) 
           LEFT JOIN products_sold ON stock.Items=products_sold.Item
         )
  Group By stock.Items

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT S.Items as Products, 
       COALESCE(PS.Quantity, 0) as [Products Sold], 
       COALESCE(PP.Quantity, 0) as [Products purchased]
From Stock S 
LEFT JOIN (SELECT Items, SUM(Quantity) AS Quantity 
           FROM products_purchased 
           GROUP BY Items
         ) AS PP ON S.Items = PP.Items 
LEFT JOIN (SELECT Items, SUM(Quantity) AS Quantity 
           FROM products_sold 
           GROUP BY Items
         ) AS PS ON S.Items = PS.Items;