Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Truy vấn MySQL đếm tần suất học sinh cùng độ tuổi?

Bạn có thể sử dụng COUNT(*) kết hợp với GROUP BY cho việc này. Trước hết, hãy tạo một bảng:

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

Chèn các bản ghi vào bảng bằng lệnh 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)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select:

mysql> select * from DemoTable;

Điều này sẽ tạo ra đầu ra sau:

+-----------+------------+
| 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)

Truy vấn sau để đếm tần suất:

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

Điều này sẽ tạo ra đầu ra sau:

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