简体   繁体   中英

Select DISTINCT and Select COUNT

An SQL query which I use seems to be having issue with counting the distinct selection. 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:

+-------------+-----------+
|  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. 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:

  SELECT item_name,
         COUNT(*) AS count
    FROM stocks
GROUP BY item_name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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