位置:首页 > 数据库 > MySQL在线教程 > MySQL Group By子句

MySQL Group By子句

可以使用GROUP BY按列的值进行分组,并且,如果愿意的话,也可对列进行计算。可以使用COUNT, SUM, AVG等函数,在上页进行列的分组计算。

要了解GROUP BY子句,我们先考虑有一个 employee_tbl表,这具有以下记录:

mysql> create table employee_tabl(
    id int(10) not null primary key auto_increment,
    name varchar(32) not null default '', 
    work_date date,
    daily_typing_pages int(10) default 0
);
Query OK, 0 rows affected (0.28 sec)

INSERT INTO employee_tabl(name, work_date,daily_typing_pages) VALUES('John', '2015-01-24', 150);
INSERT INTO employee_tabl(name, work_date,daily_typing_pages) VALUES('Ram', '2015-07-27', 220);
INSERT INTO employee_tabl(name, work_date,daily_typing_pages) VALUES('Jack', '2015-05-06', 170);
INSERT INTO employee_tabl(name, work_date,daily_typing_pages) VALUES('Jack', '2015-01-24', 100);
INSERT INTO employee_tabl(name, work_date,daily_typing_pages) VALUES('Jill', '2015-01-24', 220);
INSERT INTO employee_tabl(name, work_date,daily_typing_pages) VALUES('Zara', '2015-01-26', 300);
INSERT INTO employee_tabl(name, work_date,daily_typing_pages) VALUES('Zara', '2015-02-24', 350);

查询结果:

mysql> SELECT * FROM employee_tabl;
+------+------+------------+--------------------+
| id   | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|    1 | John | 2015-01-24 |                150 |
|    2 | Ram  | 2015-05-27 |                220 |
|    3 | Jack | 2015-05-06 |                170 |
|    3 | Jack | 2015-04-06 |                100 |
|    4 | Jill | 2015-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)

我们会看到更多相关 GROUP BY 的函数,如SUM,AVG等