0

我有一张桌子,里面放着我们售出的所有物品。订单中可能有多个项目。

我想找到订单仅包含 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 行"

谢谢你的帮助。

4

2 回答 2

2

询问:

SQLFIDDLE示例

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 |
于 2012-12-06T12:13:34.580 回答
0

试试这个:

SELECT ProductName, color, COUNT(ProductName) 
FROM (SELECT ProductName, color, orderNum FROM Items 
      GROUP BY ProductName, orderNum HAVING COUNT(orderNum)=1) AS A
于 2012-12-06T12:06:44.207 回答