Search code examples
mysqlsql-serveradventureworks

Retrieve customer who bought more than 13 different products who never purchased same product


I tried this. But I feel this gives people who ordered same product

SELECT DISTINCT Count(od.orderqty) OrderQty, 
                c.customerid, 
                od.productid 
FROM   sales.customer c 
       INNER JOIN sales.salesorderheader oh 
               ON c.customerid = oh.customerid 
       INNER JOIN sales.salesorderdetail od 
               ON oh.salesorderid = od.salesorderid 
GROUP  BY od.productid, 
          c.customerid 
HAVING Count(od.productid) > 10 
ORDER  BY c.customerid 

Solution

  • Not sure what flavor of SQL you're using but try this:

    select  t.CustomerID
    from    (
    select  c.CustomerID
            , count(distinct od.ProductID) as DistinctCount
            , count(od.ProductID) as Count
    from    Sales.Customer c
    join    Sales.SalesOrderHeader oh
            on c.customerid = oh.customerid
    join    Sales.SalesOrderDetail od
            on oh.SalesOrderID = od.SalesOrderID
    group 
    by      c.CustomerID 
    ) as t
    where   t.DistinctCount = t.Count
    and     t.DistinctCount > 13
    order 
    by      t.CustomerID