MySQL查询以字母顺序记录和计数重复项?

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

mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentGrade char(1)
   );

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

mysql> insert into DemoTable(StudentGrade) values('A');
mysql> insert into DemoTable(StudentGrade) values('F');
mysql> insert into DemoTable(StudentGrade) values('C');
mysql> insert into DemoTable(StudentGrade) values('A');
mysql> insert into DemoTable(StudentGrade) values('F');
mysql> insert into DemoTable(StudentGrade) values('F');
mysql> insert into DemoTable(StudentGrade) values('B');
mysql> insert into DemoTable(StudentGrade) values('C');

使用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)