MySQL 查询以对记录按字母排序并计算重复项?


为此,同时使用 GROUP BY 和 ORDER BY 子句。 我们先创建一个表 −

mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentGrade char(1)
   );
Query OK, 0 rows affected (0.87 sec)

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

mysql> insert into DemoTable(StudentGrade) values('A');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentGrade) values('F');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentGrade) values('C');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable(StudentGrade) values('A');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(StudentGrade) values('F');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentGrade) values('F');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentGrade) values('B');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(StudentGrade) values('C');
Query OK, 1 row affected (0.13 sec)

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

mysql> select *from DemoTable;

输出

+-----------+--------------+
| StudentId | StudentGrade |
+-----------+--------------+
| 1         | A            |
| 2         | F            |
| 3         | C            |
| 4         | A            |
| 5         | F            |
| 6         | F            |
| 7         | B            |
| 8         | C            |
+-----------+--------------+
8 rows in set (0.00 sec)

以下是按字母排序和统计的查询 −

mysql> select StudentGrade,count(StudentId) as Frequency from DemoTable 
   group by StudentGrade order by StudentGrade;

输出

+--------------+-----------+
| StudentGrade | Frequency |
+--------------+-----------+
| A            | 2         |
| B            | 1         |
| C            | 2         |
| F            | 3         |
+--------------+-----------+
4 rows in set (0.00 sec)

更新于: 2019 年 7 月 30 日

99 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告