2

顧客から複数回注文され、1 回だけ注文された製品の数を取得する必要があります。私はこれを間違った方法で見ているかもしれません.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
4

1 に答える 1

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
于 2012-09-04T03:21:13.770 に答える