统计具有相同年龄的学生的频率的 MySQL 查询?


您可以为此使用 COUNT(*) 和 GROUP BY。首先让我们创建一个表 −

mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentAge int
   );
Query OK, 0 rows affected (0.59 sec)

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

mysql> insert into DemoTable(StudentAge) values(16);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(StudentAge) values(17);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentAge) values(18);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentAge) values(17);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentAge) values(17);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(StudentAge) values(17);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(StudentAge) values(18);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentAge) values(18);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentAge) values(19);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentAge) values(19);
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(StudentAge) values(16);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentAge) values(16);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentAge) values(15);
Query OK, 1 row affected (0.16 sec)

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

mysql> select * from DemoTable;

这会产生以下输出 −

+-----------+------------+
| StudentId | StudentAge |
+-----------+------------+
| 1         | 16         |
| 2         | 17         |
| 3         | 18         |
| 4         | 17         |
| 5         | 17         |
| 6         | 17         |
| 7         | 18         |
| 8         | 18         |
| 9         | 19         |
| 10        | 19         |
| 11        | 16         |
| 12        | 16         |
| 13        | 15         |
+-----------+------------+
13 rows in set (0.00 sec)

以下是计数频率的查询 −

mysql> select StudentAge,count(*) AS `AgeFrequency` from DemoTable group by StudentAge;

这会产生以下输出 −

+------------+--------------+
| StudentAge | AgeFrequency |
+------------+--------------+
| 16         | 3            |
| 17         | 4            |
| 18         | 3            |
| 19         | 2            |
| 15         | 1            |
+------------+--------------+
5 rows in set (0.05 sec)

更新于: 30-Jul-2019

929 次查看

开启你的职业生涯

完成课程获取认证

开始
广告