Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mySQL: Multiple COUNT()s based on differing criteria

Tags:

mysql

Alright, so what I'm trying to do is perform different COUNT()s on the same table based on different criteria without nested queries (efficiency) or subqueries (so it can be made into a view). Is this possible?

Example: a table has a date column - the query should be able to produce a count of the number of rows prior to & after a constant date.

like image 543
dborba Avatar asked Aug 21 '09 19:08

dborba


1 Answers

You're using MySQL, so you can take advantage of its feature that a boolean expression evaluates to 0 for false and 1 for true. The SUM() of 1's is equal to a COUNT() where the expression is true.

SELECT SUM( date_column < '2009-08-21' ) AS prior_to_date,
       SUM( date_column > '2009-08-21' ) AS after_date
FROM MyTable;

PS: Don't try this on other brands of database that uphold the SQL standard behavior, i.e. a boolean expression yields a boolean, not a 0 or 1 integer.

like image 114
Bill Karwin Avatar answered Oct 04 '22 02:10

Bill Karwin