Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Count items in each category

Tags:

sql

database

SELECT items.id, 
       items.category, 
       COUNT(*) 
  FROM items 
 GROUP BY items.id, 
          items.category 

enter image description here
I want to display how many items in each category. For example,
category 1 - 6
category 2 - 7
category 3 - 4 ...
Please help me! I try this request and show me all the items with category :/

like image 818
Omar Krichen Avatar asked Nov 30 '25 23:11

Omar Krichen


2 Answers

Try this...

SELECT items.category, 
       COUNT(*) AS Count 
FROM   items 
GROUP  BY items.category 
like image 70
DxTx Avatar answered Dec 03 '25 13:12

DxTx


Please use 'distinct'

SELECT distinct items.category, 
       COUNT(*) AS Count 
FROM   items 
GROUP  BY items.category

to get the correct count for each unique category

like image 31
Vitalii Chornobryvyi Avatar answered Dec 03 '25 15:12

Vitalii Chornobryvyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!