Conditional count mysql

In the process of website development, often use statistical functions, thus counting the query conditions is inevitable, here are several ways to solve this problem.

Example (hypothetical):

MySQL >  the SELECT  *  from count_demo;
 + - ----- + ------ + ----- + 
| class | Pass | Sex | 
+ - ----- + ----- - + ----- + 
|      2  |     1  | M   | 
|      2  |     0  | F   | 
|      1  |     1  | M   | 
|      3  |     1  | F   | 
|      5  |     1  | M   |
|      4  |     0  | F   | 
|      1  |     0  | F   | 
|      2  |     1  | M   | 
|      6  |     0  | M   | 
+ - ----- + ------ + ----- + 

in rows 9 the SET

 

Available statistics a year as an exam (class representative of class, pass exams indicate whether through, 1 through 0 to fail, sex is sex) by recording the table.

Now need statistics, passed the exam for each class and the number did not pass the exam.

 

Method a: Use OR NULL

mysql> select count(pass=1 or null) as pass,count(pass=0 or null) as no_pass,class from count_demo group by class;
+------+---------+-------+
| pass | no_pass | class |
+------+---------+-------+
|    1 |       1 |     1 |
|    2 |       1 |     2 |
|    1 |       0 |     3 |
|    0 |       1 |     4 |
|    1 |       0 |     5 |
|    0 |       1 |     6 |
+------+---------+-------+
6 rows in set

 

Wherein Note that "or null" is used, the number of values ​​of COUNT (column_name) function returns the specified column (NULL not included) Manual mentioned, if it is not equal to 1 when the pass, or null to act, let condition is null, then the count will not be calculated not pass a value of 1. That is correct statistics. (Removable self-test or null, the result is wrong)


Method Two: Use multiple select

mysql> select count(pass) as pass,class from count_demo where pass=1 group by class;
+------+-------+
| pass | class |
+------+-------+
|    1 |     1 |
|    2 |     2 |
|    1 |     3 |
|    1 |     5 |
+------+-------+
4 rows in set

 

mysql> select count(pass) as pass,class from count_demo where pass=0 group by class;
+------+-------+
| pass | class |
+------+-------+
|    1 |     1 |
|    1 |     2 |
|    1 |     4 |
|    1 |     6 |
+------+-------+
4 rows in set

This is very intuitive and very simple, if less statistical conditions is recommended.

 

Method three: Use CASE WHEN

mysql> select count(case when pass=1 then 1 else null end)as pass,count(case when pass=0 then 1 else null end)as no_pass,class 
from count_demo group by class;


+------+---------+-------+
| pass | no_pass | class |
+------+---------+-------+
|    1 |       1 |     1 |
|    2 |       1 |     2 |
|    1 |       0 |     3 |
|    0 |       1 |     4 |
|    1 |       0 |     5 |
|    0 |       1 |     6 |
+------+---------+-------+
6 rows in set

Function CASE WHEN statement is very powerful, you can define flexible query conditions, it is suitable to classify statistics.

Guess you like

Origin www.cnblogs.com/RyanJin/p/11731694.html