在MySQL查询中如何在CASE条件下使用count?
在MySQL中为此使用CASE WHEN,并在COUNT()
方法内设置CASE条件以进行计数。让我们首先创建一个表-
mysql> create table DemoTable1374-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20),
-> Score int
-> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1374(Name,Score) values('Chris',45);mysql> insert into DemoTable1374(Name,Score) values('David',78);
mysql> insert into DemoTable1374(Name,Score) values('Bob',45);
mysql> insert into DemoTable1374(Name,Score) values('Mike',75);
mysql> insert into DemoTable1374(Name,Score) values('Carol',45);
mysql> insert into DemoTable1374(Name,Score) values('Adam',89);
使用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查询中如何在CASE条件下使用count? 的全部内容, 来源链接: utcz.com/z/356364.html