The use of GROUP BY clause in MySQL is briefly introduced

  • 2020-10-31 22:01:18
  • OfStack

You can use the GROUP BY group to value 1 column, and you can calculate that column if you wish. Grouping columns using COUNT, SUM, AVG, etc.

To understand that the GROUP BY clause considers the table of EMPLOYEE_TBL to have the following records:


mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id  | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
|  1 | John | 2007-01-24 |        250 |
|  2 | Ram | 2007-05-27 |        220 |
|  3 | Jack | 2007-05-06 |        170 |
|  3 | Jack | 2007-04-06 |        100 |
|  4 | Jill | 2007-04-06 |        220 |
|  5 | Zara | 2007-06-06 |        300 |
|  5 | Zara | 2007-02-06 |        350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)

Now, assume that based on the above table, we want to calculate the number of days worked per employee.
If we were to write an SQL query, as shown below, we would get the following result:


mysql> SELECT COUNT(*) FROM employee_tbl;
+---------------------------+
| COUNT(*)         |
+---------------------------+
| 7             |
+---------------------------+


However, this is not our intended service; we want to display the total number of pages entered per person individually. This is done by using the aggregate function 1 using the GROUP BY clause as follows:


mysql> SELECT name, COUNT(*)
  -> FROM  employee_tbl 
  -> GROUP BY name;
+------+----------+
| name | COUNT(*) |
+------+----------+
| Jack |    2 |
| Jill |    1 |
| John |    1 |
| Ram |    1 |
| Zara |    2 |
+------+----------+
5 rows in set (0.04 sec)


Related articles: