如何在 MySQL 查询中同时使用 count 和 CASE 条件?
为此在 MySQL 中使用 CASE WHEN 并设置 COUNT() 方法内部的 CASE 条件来计数。让我们首先创建一个表 -
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)
广告