简体   繁体   English

选择具有唯一值的行数

[英]Select count of rows with unique values

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. 我想找到最受欢迎的项目颜色组合,其中订单仅包含1个项目。 I'm wondering if it's possible to find this in one MySQL statement (maybe using nested Selects). 我想知道是否可以在一个MySQL语句中找到它(可能使用嵌套的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. 实际上我有很多产品和50多种颜色。

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" - “子查询返回超过1行”

Thanks for your help. 谢谢你的帮助。

Query: 查询:

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

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM