MySQL查询 - 求和一个相关表 - 计算另一个相关表

时间:2012-07-25 14:46:25

标签: mysql

Count使用一个相关的表可以正常工作,但是当我添加Sum时,我会在Count中得到过度膨胀的结果。

SELECT Orders.kp_OrderID AS `Order #`, 
    Orders.t_ServiceLevel AS `Service Level`, 
    Customers.t_CustCompany AS Company, 
    Orders.t_JobName AS `Job Name`, 
    Orders.t_JobStatus AS `Status`, 
    Orders.d_JobDue AS Due, 
    Orders.ti_JobDue AS Time, 
    COUNT(OrderItems.kf_OrderID) AS `Line Item`, 
    SUM(
        `OrderItemComponents`.`n_QuantityPrintMaterial` * (
        `OrderItemComponents`.`n_WidthInInches` * `OrderItemComponents`.`n_HeightInInches` / 144
            )
        ) AS SqFt, 
    Orders.nb_JobFinished AS Finished
FROM Orders 
     INNER JOIN OrderItems ON Orders.kp_OrderID = OrderItems.kf_OrderID
     INNER JOIN Customers ON Orders.kf_CustomerID = Customers.kp_CustomerID
     INNER JOIN OrderItemComponents ON OrderItemComponents.kf_OrderID = Orders.kp_OrderID
    WHERE Orders.d_JobDue > (
        DATE_SUB(CURDATE(), INTERVAL 60 DAY)
         )
    GROUP BY Orders.kp_OrderID
    ORDER BY `Line Item` DESC

2 个答案:

答案 0 :(得分:2)

将您的COUNT行切换为:

COUNT(DISTINCT OrderItems.kf_OrderID) AS `Line Item`

添加行

INNER JOIN OrderItemComponents 
  ON OrderItemComponents.kf_OrderID = Orders.kp_OrderID

你返回了更多的行,因为我认为OrderItem可以包含多个组件。

<强>更新

如果您的COUNT语句:

,请尝试使用此方法
(SELECT COUNT(OrderItems.kf_OrderID) 
 FROM OrderItems.kf_OrderID 
 WHERE OrderItems.kf_OrderID=Order.kf_OrderID) AS `Line Item`,

答案 1 :(得分:1)

我假设您为每个订单商品组件重复了每个订单商品。一种解决方案可能是COUNT(DISTINCT OrderItems.kf_OrderID),因此您不必对同一项目进行两次计算。