如何在MySQL查询中使用带有CASE条件的count?
在MySQL中,可以使用CASE WHEN和将CASE条件设置在COUNT()方法中来计数。先创建一个表,如下所示 −
mysql> create table DemoTable1374
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20),
-> Score int
-> );
Query OK, 0 rows affected (0.61 sec)
使用INSERT命令向表中插入一些记录,如下所示−
mysql> insert into DemoTable1374(Name,Score) values('Chris',45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1374(Name,Score) values('David',78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1374(Name,Score) values('Bob',45);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1374(Name,Score) values('Mike',75);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1374(Name,Score) values('Carol',45);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1374(Name,Score) values('Adam',89);
Query OK, 1 row affected (0.18 sec)
使用SELECT语句显示表中的所有记录−
mysql> select * from DemoTable1374;
此命令会产生以下输出结果−
+----+-------+-------+
| Id | Name | Score |
+----+-------+-------+
| 1 | Chris | 45 |
| 2 | David | 78 |
| 3 | Bob | 45 |
| 4 | Mike | 75 |
| 5 | Carol | 45 |
| 6 | Adam | 89 |
+----+-------+-------+
6 rows in set (0.00 sec)
使用以下查询语句进行CASE WHEN条件设置并计数−
mysql> select count( case when Score=45 then 1 else NULL end) as SpecificCondition from DemoTable1374;
此命令会产生以下输出结果−
+-------------------+
| SpecificCondition |
+-------------------+
| 3 |
+-------------------+
1 row in set (0.00 sec)
阅读更多:MySQL 教程