Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting distinct items within a category on SQL

Tags:

sql

php

mysql

count

I need to compose a SQL statement as follows:

I have a table with many items, each item having a category. In total there are 3 categories.

I need to select the DISTINCT categories and then order them by number of items within each category.

Would this be a good way? Or too slow?

SELECT DISTINCT category, count(*) AS counter
FROM item_descr
GROUP BY category
ORDER BY counter DESC
like image 374
samyb8 Avatar asked Feb 01 '13 19:02

samyb8


People also ask

How do I count the number of categories in SQL?

SQL COUNT( ) with group by and order by In this page, we are going to discuss the usage of GROUP BY and ORDER BY along with the SQL COUNT() function. The GROUP BY makes the result set in summary rows by the value of one or more columns. Each same value on the specific column will be treated as an individual group.

How do I count the number of values in a column in SQL?

SELECT COUNT(ALL column_name) FROM table_name; The ALL keyword will count all values in the table including duplicates. You can omit this keyword because the COUNT function uses the ALL keyword as the default whether you write it or not.

How do you do a distinct count?

Right-click on any value in column B. Go to Value Field Settings. In the Summarize Values By tab, go to Summarize Value field by and set it to Distinct Count.


1 Answers

The DISTINCT is not needed since you are using GROUP BY category:

SELECT category, count(*) AS counter
FROM item_descr
GROUP BY category
ORDER BY counter DESC
like image 145
Taryn Avatar answered Nov 03 '22 00:11

Taryn