Group result in MySQL and show on list?

MySQLMySQLi Database

For this, use GROUP BY along with ORDER BY −

select yourColumnName,count(*) as anyAliasName from yourTableName group by yourColumnName order by yourColumnName;

Let us create a table −

mysql> create table demo7
−> (
−> id int NOT NULL AUTO_INCREMENT,
−> first_name varchar(50)
−> ,
−> primary key(id)
−> );
Query OK, 0 rows affected (1.22 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo7(first_name) values('John');
Query OK, 1 row affected (0.09 sec)
mysql> insert into demo7(first_name) values('David');
Query OK, 1 row affected (0.22 sec)
mysql> insert into demo7(first_name) values('John');
Query OK, 1 row affected (0.07 sec)
mysql> insert into demo7(first_name) values('Bob');
Query OK, 1 row affected (0.27 sec)
mysql> insert into demo7(first_name) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into demo7(first_name) values('David');
Query OK, 1 row affected (0.09 sec)
mysql> insert into demo7(first_name) values('John');
Query OK, 1 row affected (0.26 sec)
mysql> insert into demo7(first_name) values('John');
Query OK, 1 row affected (0.09 sec)

Display records from the table using select statement −

mysql> select *from demo7;

This will produce the following output −

+----+------------+
| id | first_name |
+----+------------+
|  1 | John       |
|  2 | David      |
|  3 | John       |
|  4 | Bob        |
|  5 | David      |
|  6 | David      |
|  7 | John       |
|  8 | John       |
+----+------------+
8 rows in set (0.00 sec)

Following is the query to group result in MySQL and show on list −

mysql> select first_name,count(*) as frequency from demo7 group by first_name order by first_name;

This will produce the following output −

+------------+-----------+
| first_name | frequency |
+------------+-----------+
| Bob        |         1 |
| David      |         3 |
| John       |         4 |
+------------+-----------+
3 rows in set (0.00 sec)
raja
Published on 19-Nov-2020 15:27:39
Advertisements