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?
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.
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.
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.
You can GROUP BY multiple columns, to get the count of each combination.
SELECT color, COUNT(*) FROM t_table GROUP BY color
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With