假设我有一张记录服装店交易的表格。每件商品都有不同的种类(如不同的颜色)。我想编写一个查询,返回每件商品的售出数量,同时告诉我每件商品售出了多少种不同的颜色。
所以如果我有这样一张表:
+------------+
|transactions|
+------+-------+
| item | color |
+------+-------+
|shirt | red |
|shirt | red |
|shirt | blue |
|shirt | green |
|hat | blue |
|hat | red |
|pants | blue |
|pants | blue |
|pants | blue |
+------+-------+
我想要一个看起来像这样的结果:
+------+-------+--------+
| item | count | colors |
+------+-------+--------+
|shirt | 4 | 3 |
|hat | 2 | 2 |
|pants | 3 | 1 |
+------+-------+--------+
获取每件商品的销售数量非常简单。我知道我可以使用如下查询:
SELECT item, COUNT(*) as count FROM transactions GROUP BY item
我不确定的部分是如何计算每个项目的不同颜色的数量。
最佳答案
你正在寻找count(distinct)
:
SELECT item, COUNT(*) as num, COUNT(DISTINCT color) as num_colors
FROM transactions
GROUP BY item;
关于MYSQL统计每类item的颜色数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46688084/