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


为此,您可以使用聚合函数 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)

更新于: 02-7-2020

174 次浏览

提升您的 事业

完成课程即可获得认证

开始学习
广告