选择具有唯一值的行数

时间:2012-12-05 22:56:53

标签: mysql nested-sets

我有一张桌子,上面有我们售出的所有物品。订单中可能有多个商品。

我想找到最受欢迎的商品颜色组合,其中订单仅包含1件商品。 我想知道是否可以在一个MySQL语句中找到它(可能使用嵌套的Selects)。到目前为止,我已经尝试了几件事但没有成功。

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

所以“

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

会显示:

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

实际上我有很多产品和50多种颜色。

我尝试了什么:

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

- “子查询返回超过1行”

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

查询:

<强> 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

结果:

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

答案 1 :(得分:0)

试试这个:

SELECT ProductName, color, COUNT(ProductName) 
FROM (SELECT ProductName, color, orderNum FROM Items 
      GROUP BY ProductName, orderNum HAVING COUNT(orderNum)=1) AS A