Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

레코드를 알파벳순으로 정렬하고 중복을 계산하는 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)

삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -

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)