2012-09-04 90 views
2

我需要獲得多次訂購的產品的數量並且僅由客戶訂購一次。我可能正在看這個錯誤的方式,請原諒我,如果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 

從正從子查詢計數的吳宇森的想法,我想出了這個代碼,它實際上做的工作,但有點嵌套。也許你們可以幫助我提高效率或縮短時間。再次感謝所有的幫助!

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 

回答

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 
+0

嗨約翰總數。我似乎無法使您的代碼正常工作,但我能夠從您從子查詢中獲取計數的想法中工作。雖然它有點嵌套。我會在我的問題上發佈代碼。也許你們可以想出一個更有效率的。 –

+0

@MarcelLainez在我看來,你當前的查詢效果很好,因爲你不能在同一個查詢上聚合聚合列,例如'SUM(COUNT(DISTINCT OrderNumber))' –

+0

是的,我最初嘗試了這一點。呵呵。再次感謝! –