在 MySQL 中按条件计数?
要计数,使用聚合函数 SUM(),要使用条件计数,你需要使用 WHERE 设置条件。我们首先创建一个表 -
mysql> create table DemoTable1515 -> ( -> ClientId varchar(10), -> ClientName varchar(20) -> ); Query OK, 0 rows affected (0.53 sec)
使用插入命令向表中插入一些记录 -
mysql> insert into DemoTable1515 values('CLI-101','Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1515 values('CLI-110','David'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1515 values('CLI-101','Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1515 values('CLI-101','Sam'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1515 values('CLI-101','Sam'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1515 values('CLI-101','Mike'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1515 values('CLI-130','Mike'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1515 values('CLI-101','Chris'); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable1515 values('CLI-101','Sam'); Query OK, 1 row affected (0.18 sec)
使用选择语句从表中显示所有记录 -
mysql> select * from DemoTable1515;
这将产生以下输出 -
+----------+------------+ | ClientId | ClientName | +----------+------------+ | CLI-101 | Chris | | CLI-110 | David | | CLI-101 | Bob | | CLI-101 | Sam | | CLI-101 | Sam | | CLI-101 | Mike | | CLI-130 | Mike | | CLI-101 | Chris | | CLI-101 | Sam | +----------+------------+ 9 rows in set (0.00 sec)
以下是使用条件计数的查询 -
mysql> select ClientId,sum(ClientName='Sam') as NameOn101Id,count(*) as TotalNameOn101 from DemoTable1515 -> where ClientId='CLI-101';
这将产生以下输出 -
+----------+-------------+----------------+ | ClientId | NameOn101Id | TotalNameOn101 | +----------+-------------+----------------+ | CLI-101 | 3 | 7 | +----------+-------------+----------------+ 1 row in set (0.00 sec)
广告