Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL find total count of each type in a column

Tags:

I'm learning SQL and am stumped on what should be a simple query. I have a table with the following pattern:

Id |  Type   ------------ 1  |  Red    2  |  Blue   3  |  Blue   4  |  Red    .. 

I would like to write a query to return a table that counts the total number of instances of each type and returns a table with the following pattern, for example, if 'Blue' occurs in 12 rows, and 'Red' occurs in 16 rows in the table above, the result would be:

Blue | Red  -----------  12  |  16  
like image 746
Wes Doyle Avatar asked Sep 15 '15 20:09

Wes Doyle


People also ask

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 I count the number of rows in SQL based on one column?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do you use count in GROUP BY clause?

SQL – count() with Group By clause The count() function is an aggregate function use to find the count of the rows that satisfy the fixed conditions. The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.


1 Answers

You could do it this way:

SELECT Type, COUNT(*) FROM TABLE GROUP BY Type 

If you'd like to see the Types in separate columns, you could do this:

SELECT SUM(CASE WHEN Type = 'Blue' THEN 1 ELSE 0 END) AS Blue, SUM(CASE WHEN Type = 'Red' THEN 1 ELSE 0 END) AS Red FROM TABLE 
like image 135
Will Avatar answered Sep 20 '22 16:09

Will