[英]Select DISTINCT and Select COUNT
An SQL query which I use seems to be having issue with counting the distinct selection. 我使用的SQL查询似乎在计算不同的选择时遇到问题。 Here is the query:
这是查询:
SELECT DISTINCT a.item_name,
(SELECT count(c.item_name) FROM stocks c
WHERE a.item_name = c.item_name) as 'count'
FROM stocks a;
I have 4 rows containing apple
and 2 rows containing banana
in my database with different barcodes as follows: 我的数据库中有4行包含
apple
和2行包含banana
行,其中包含不同的条形码,如下所示:
+-------------+-----------+
| item_name | barcode |
+-------------+-----------+
| apple | 1283123 |
| apple | 1231231 |
| apple | 1231312 |
| apple | 1231312 |
| bananas | 1231312 |
| bananas | 1231312 |
+-------------+-----------+
Using the query above give me output of 使用上面的查询给我输出
+-------------+-----------+
| item_name | barcode |
+-------------+-----------+
| apple | 5 |
| bananas | 2 |
+-------------+-----------+
The query always adds 1 count to the first row. 查询始终向第一行添加1个计数。 What is wrong with my query?
我的查询有什么问题?
Why do you need a join at all? 为什么你需要加入? Using
COUNT()
with a GROUP BY
will provide you with the same desired result: 将
COUNT()
与GROUP BY
将为您提供相同的所需结果:
SELECT item_name,
COUNT(*) AS count
FROM stocks
GROUP BY item_name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.