Question

I have a table that holds all of the items we have sold. There may be more than one item in an Order.

I want to find the most popular item-color combinations where an order contains ONLY 1 item. I'm wondering if it's possible to find this in one MySQL statement (maybe using nested Selects). I've tried several things with no success so far.

ProductName | Color | OrderNum | 
--------------------------------
productA    | black | 1
productA    | black | 1
productA    | black | 2
productA    | black | 3
productA    | black | 4
productA    | black | 4
productA    | black | 5

so "

SELECT COUNT(ProductName), ProductName WHERE ~~COUNT(OrderNum)=1~~ GROUP BY ProductName, Color

would show:

COUNT(ProductName) | ProductName | Color
      3            | ProductA    | black

In reality I have scores of products and over 50 colors.

What I've tried:

SELECT COUNT(ProductName), ProductName,Color, 
       (SELECT COUNT(OrderNum) FROM Items GROUP BY OrderNum) AS itemcount 
FROM Items WHERE 1 
GROUP BY ProductName,Color HAVING itemcount = 1

SELECT COUNT( ProductName ) , ProductName, Color
FROM Items
WHERE (SELECT COUNT( OrderNum ) AS itemcounts
       FROM Items GROUP BY OrderNum
) =1
GROUP BY ProductName

--"Subquery returns more than 1 row"

Thanks for your help.

Was it helpful?

Solution

Query:

SQLFIDDLEExample

SELECT
COUNT(*) as count, i.ProductName, i.Color
FROM ITems i
WHERE 1 = (SELECT COUNT( OrderNum ) AS itemcounts
           FROM Items 
           WHERE OrderNum = i.OrderNum
           )
GROUP BY ProductName, Color

Result:

| COUNT | PRODUCTNAME | COLOR |
-------------------------------
|     3 |    productA | black |

OTHER TIPS

Try this:

SELECT ProductName, color, COUNT(ProductName) 
FROM (SELECT ProductName, color, orderNum FROM Items 
      GROUP BY ProductName, orderNum HAVING COUNT(orderNum)=1) AS A
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top