Home  >  Article  >  Database  >  简单介绍MySQL中GROUP BY子句的使用_MySQL

简单介绍MySQL中GROUP BY子句的使用_MySQL

WBOY
WBOYOriginal
2016-06-01 13:00:18847browse

 可以使用GROUP BY组值一列,并且如果愿意的话,可以将该列进行计算。使用COUNT,SUM,AVG等功能的分组列。

要了解GROUP BY子句考虑的EMPLOYEE_TBL的的表具有以下记录:

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)

现在,假设根据上表,我们希望计算每一位员工工作的天数。
如果我们将编写一个SQL查询,如下所示,那么我们将得到下面的结果:

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


但是,这不是我们的目的服务,我们要显示输入的每个人单独的页面总数。这是通过使用聚合函数一起用GROUP BY子句如下:

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)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn