MySQL query to alphabetize records and count the duplicates?


For this, use both GROUP BY and ORDER BY clause. Let us first create a table −

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

Insert some records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

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

Here is the query to alphabetize and count −

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

Output

+--------------+-----------+
| StudentGrade | Frequency |
+--------------+-----------+
| A            | 2         |
| B            | 1         |
| C            | 2         |
| F            | 3         |
+--------------+-----------+
4 rows in set (0.00 sec)
raja
Published on 13-Jun-2019 12:04:21
Advertisements