I need to get the count of a product that was ordered more than once and ordered only once by customers. I may be looking at this the wrong way, please forgive me if the sql looks stupid or something.
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
From John Woo's idea of getting the count from the subquery, I came up with this code, which actually does work, but a bit nested. Maybe you guys can help me make this more efficient or at least shorter. Thanks again for all the help!
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