【问题标题】:MySQL query Select, SUM, LEFT JOINMySQL 查询 Select、SUM、LEFT JOIN
【发布时间】:2015-02-22 15:17:59
【问题描述】:

名为 stock 的表 1 包含列 Items
名为 Products_sold 的表 2 包含 商品、数量
名为 products_purchased 的表 3 包含 Items, Quantity

我需要获取三列的 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

【问题讨论】:

  • 编辑您的问题并尝试解决此问题。

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


【解决方案1】:

试试这个:

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; 

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2014-05-23
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多