It can be done by using GROUP BY clause in the SELECT statement. We can specify a column as grouping criteria with the help of GROUP BY clause. Due to the specified grouping criteria, rows with the same value in a particular column are considered as a single group. In this way, the result set returned by MySQL SELECT statement will be divided into groups.
Example
Following is a good example to understand it −
We have a table named ‘employees’ as follows −
mysql> Select * from employees; +------+-------------+--------+------------+ | id | designation | Salary | DoJ | +------+-------------+--------+------------+ | 100 | Asst.Prof | 50000 | 2016-06-15 | | 300 | Prof | 85000 | 2010-05-18 | | 250 | Asso.Prof | 74000 | 2013-02-12 | | 400 | Prof | 90000 | 2009-05-19 | | 200 | Asst.Prof | 60000 | 2015-05-11 | +------+-------------+--------+------------+ 5 rows in set (0.00 sec)
Now with the help of following script we will divide the output into groups;
mysql> select designation, count(*), AVG(salary) from employees group by designation; +-------------+----------+-------------+ | designation | count(*) | AVG(salary) | +-------------+----------+-------------+ | Asso.Prof | 1 | 74000.0000 | | Asst.Prof | 2 | 55000.0000 | | Prof | 2 | 87500.0000 | +-------------+----------+-------------+ 3 rows in set (0.00 sec)
Above query returns the result set into groups of Asso.Prof, total 1 in number and having average salary 74000, Asst.Prof, total 2 in number and having an average salary of 55000 and Prof, total 2 in number and having average salary 87500.