在 MySQL 中计算已知不同值的出现次数

mysqlmysqli database

为此,您可以使用聚合函数 SUM()。让我们首先创建一个表 −

mysql> create table DemoTable636 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentFirstName varchar(100)
);
Query OK, 0 rows affected (0.51 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable636(StudentFirstName) values('John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Robert');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Sam');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Mike');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable636(StudentFirstName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Robert');
Query OK, 1 row affected (0.16 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable636;

这将产生以下输出 −

+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
|         1 | John             |
|         2 | Robert           |
|         3 | Robert           |
|         4 | Sam              |
|         5 | Mike             |
|         6 | John             |
|         7 | Robert           |
+-----------+------------------+
7 rows in set (0.00 sec)

以下查询用于计算已知(或枚举)不同值的出现次数 −

mysql> select
   sum(StudentFirstName='John') AS JOHN_COUNT,
   sum(StudentFirstName='Robert') AS ROBERT_COUNT,
   sum(StudentFirstName='Sam') AS SAM_COUNT,
   sum(StudentFirstName='Mike') AS MIKE_COUNT
   from DemoTable636;

这将产生以下输出 −

+------------+--------------+-----------+------------+
| JOHN_COUNT | ROBERT_COUNT | SAM_COUNT | MIKE_COUNT |
+------------+--------------+-----------+------------+
|          2 |            3 | 1         | 1          |
+------------+--------------+-----------+------------+
1 row in set (0.00 sec)

相关文章