mySQL: Multiple COUNT()s based on differing criteria

后端 未结 1 829
感情败类
感情败类 2021-02-05 20:00

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 ma

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 20:26

    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.

    0 讨论(0)
提交回复
热议问题