0

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
4

2 回答 2

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`,
于 2012-07-25T14:54:25.157 回答
1

我假设您为每个订单项目组件重复每个订单项目。一种解决方案可能是COUNT(DISTINCT OrderItems.kf_OrderID)这样您就不会重复计算同一项目。

于 2012-07-25T14:55:26.653 回答