Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple COUNT() for multiple conditions in one query (MySQL)

Tags:

sql

mysql

count

I have these queries :

SELECT COUNT(*) FROM t_table WHERE color = 'YELLOW'; SELECT COUNT(*) FROM t_table WHERE color = 'BLUE'; SELECT COUNT(*) FROM t_table WHERE color = 'RED'; 

Is there any way to get these results in one query?

like image 288
TrtG Avatar asked Sep 27 '13 09:09

TrtG


People also ask

How do I count multiple criteria in SQL?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table.

What is the difference between count () and count (*) function in MySQL?

Difference between count(*) and count(columnName) in MySQL? The count(*) returns all rows whether column contains null value or not while count(columnName) returns the number of rows except null rows.

How do I sum multiple counts in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

Can we use count on multiple columns in SQL?

You can GROUP BY multiple columns, to get the count of each combination.


2 Answers

SELECT color, COUNT(*) FROM t_table GROUP BY color 
like image 103
eggyal Avatar answered Sep 24 '22 06:09

eggyal


If you want the result to be in one row you can use:

SELECT     SUM(IF(color = 'YELLOW', 1, 0)) AS YELLOW,     SUM(IF(color = 'BLUE', 1, 0)) AS BLUE,     SUM(IF(color = 'RED', 1, 0)) AS RED FROM t_table 

Working example

like image 30
eisberg Avatar answered Sep 24 '22 06:09

eisberg