计数产品不止一次订购

时间:2012-09-04 03:20:06

标签: mysql

我需要获得不止一次订购的产品的数量,并且只能由客户订购一次。我可能会以错误的方式看待这个问题,请原谅我,如果sql看起来很蠢或什么的。

SELECT ActualOrder.Sku,
COUNT(DISTINCT Email) AS UniqueCustomer,
COUNT(DISTINCT OrderNumber) AS NumOrders,
COUNT(Reordered.Sku) AS NumReordered,
COUNT(OrderedOnce.Sku) AS NumOrderedOnce
FROM ActualOrder
LEFT JOIN (SELECT Sku FROM ActualOrder GROUP BY Email HAVING COUNT(DISTINCT OrderNumber) > 1) AS Reordered ON ActualOrder.Sku = Reordered.Sku
LEFT JOIN (SELECT Sku FROM ActualOrder GROUP BY Email HAVING COUNT(DISTINCT OrderNumber) = 1) AS OrderedOnce ON ActualOrder.Sku = OrderedOnce.Sku
GROUP BY ActualOrder.Sku

从John Woo关于从子查询中获取计数的想法,我想出了这个代码,它实际上可行,但有点嵌套。也许你们可以帮助我提高效率或者至少更短。再次感谢您的帮助!

SELECT ActualOrder.Sku,
COUNT(DISTINCT Email) AS UniqueCustomer,
COUNT(DISTINCT OrderNumber) AS NumOrders,
NumReordered,
NumOrderedOnce
FROM ActualOrder
LEFT JOIN (SELECT Sku, SUM(IF(NumCustomerOrders>1,1,0)) AS NumReordered, SUM(IF(NumCustomerOrders=1,1,0)) AS NumOrderedOnce
    FROM (SELECT Sku, Email, COUNT(DISTINCT OrderNumber) AS NumCustomerOrders
        FROM ActualOrder GROUP BY Sku, Email)
    AS Orders GROUP BY Sku) AS OrderCount ON ActualOrder.Sku = OrderCount.Sku
GROUP BY ActualOrder.Sku

1 个答案:

答案 0 :(得分:2)

您可以计算subquery

上的订单总数
SELECT  ActualOrder.Sku,
        Reordered.NumReordered,
        OrderedOnce.NumOrderedOnce
        COUNT(DISTINCT Email) AS UniqueCustomer,
        COUNT(DISTINCT OrderNumber) AS NumOrders
FROM ActualOrder
        LEFT JOIN 
        (
            SELECT Sku, COUNT(*) NumReordered
            FROM ActualOrder 
            GROUP BY Email 
            HAVING COUNT(*) > 1
        ) AS Reordered ON ActualOrder.Sku = Reordered.Sku
        LEFT JOIN 
        (
            SELECT Sku, COUNT(*) NumOrderedOnce
            FROM ActualOrder 
            GROUP BY Email 
            HAVING COUNT(*) = 1
        ) AS OrderedOnce ON ActualOrder.Sku = OrderedOnce.Sku
GROUP BY    ActualOrder.Sku,
            Reordered.NumReordered,
            OrderedOnce.NumOrderedOnce