SQL查询中的多个SUM,包括LEFT JOIN

时间:2019-03-08 13:43:47

标签: sql left-join

我想显示特定客户的所有工作订单,以及他欠我们的款项。

我的问题是,在当前查询中,只要有一个以上的产品(“ Work_Order_Products”表),乘以“ Work_Order_Products”表返回的记录数即可。

有没有办法解决这个问题? 谢谢

SELECT
    W.ID_WorkOrder AS ID_WorkOrder,
    W.Number AS Number,
    W.Date AS Date,
    C.Name AS Name,
    SUM(WOP.Quantity * WOP.Price) AS totProducts,
    SUM(WOI.Times) AS totTimes
FROM Work_Order W
LEFT JOIN Work_Order_Products WOP ON WOP.ID_WorkOrder = W.ID_WorkOrder
LEFT JOIN Work_Order_Instructions WOI ON WOI.ID_WorkOrder = W.ID_WorkOrder
LEFT JOIN Customers C ON C.ID_WorkOrder = W.ID_Customer
WHERE W.ID_Customer = x
GROUP BY
    ID_WorkOrder,
    Number,
    Date,
    Name

3 个答案:

答案 0 :(得分:1)

我将尝试使用相关子查询而不是SUM:

替换:

SUM(WOI.Times) AS totTimes

具有:

(
    select SUM(WOI.Times) from Work_Order_Instructions WOI
    where
        WOI.ID_WorkOrder = W.ID_WorkOrder

) as totTimes

答案 1 :(得分:0)

按照克里斯的建议,这可能会起作用:

SELECT
    W.ID_WorkOrder AS ID_WorkOrder,
    W.Number AS Number,
    W.Date AS Date,
    C.Name AS Name,
    products.ProductCount AS totProducts,
    Instructions.totTimes AS totTimes
FROM Work_Order W
    LEFT JOIN
        (SELECT WOP.ID_WorkOrder, SUM(WOP.Quantity * WOP.Price) AS ProductCount
        FROM Work_Order_Products WOP
        GROUP BY WOP.ID_WorkOrder) AS products
    ON  products.ID_WorkOrder = W.ID_WorkOrder
    LEFT JOIN
        (SELECT WOI.ID_WorkOrder, SUM(WOI.Times) AS totTimes
        FROM Work_Order_Instructions WOI
        GROUP BY WOI.ID_WorkOrder) AS Instructions
    ON Instructions.ID_WorkOrder = W.ID_WorkOrder
    LEFT JOIN Customers C ON C.ID_WorkOrder = W.ID_Customer
WHERE W.ID_Customer = x
GROUP BY
    W.ID_WorkOrder,
    Number,
    Date,
    Name

也就是说,使用括号创建“子表”,这将需要它们自己的别名。 (这里可能存在语法错误。当然,我没有运行此数据。)

答案 2 :(得分:0)

为了避免Work_Order_ProductsWork_Order_Instructions表中的乘数,请在加入表之前处理汇总。

SELECT
  W.ID_WorkOrder AS ID_WorkOrder
 ,W.Number AS Number
 ,W.Date AS Date
 ,C.Name AS Name
 ,WOP.totProducts
 ,WOI.totTimes
FROM
  Work_Order AS W
LEFT JOIN
  (
    SELECT 
      ID_WorkOrder
      ,SUM(Quantity * Price) AS totProducts
    FROM
      Work_Order_Products
    GROUP BY
      ID_WorkOrder

  ) AS WOP
    ON
    WOP.ID_WorkOrder = W.ID_WorkOrder
LEFT JOIN
  (
    SELECT 
      ID_WorkOrder
      ,SUM(Times) AS totTimes
    FROM
      Work_Order_Instructions
    GROUP BY
      ID_WorkOrder
  ) AS WOI
    ON
    WOI.ID_WorkOrder = W.ID_WorkOrder
LEFT JOIN
  Customers AS C
    ON
    C.ID_WorkOrder = W.ID_Customer
WHERE
  W.ID_Customer = x;