扫码一下
查看教程更方便
group by 语句根据一个或多个列对结果集进行分组。
在分组的列上我们可以使用 count, sum, avg,等函数。
select column_name, function(column_name)
from table_name
where column_name operator value
group by column_name;
本章节示例使用到了以下表结构及数据,使用前我们可以先将以下数据导入数据库中。
set names utf8;
set foreign_key_checks = 0;
-- ----------------------------
-- table structure for `employee_tbl`
-- ----------------------------
drop table if exists `employee_tbl`;
create table `employee_tbl` (
`id` int(11) not null,
`name` char(10) not null default '',
`date` datetime not null,
`singin` tinyint(4) not null default '0' comment '登录次数',
primary key (`id`)
) engine=innodb default charset=utf8;
-- ----------------------------
-- records of `employee_tbl`
-- ----------------------------
begin;
insert into `employee_tbl` values ('1', '小明', '2016-04-22 15:25:33', '1'), ('2', '小王', '2016-04-20 15:25:47', '3'), ('3', '小丽', '2016-04-19 15:26:02', '2'), ('4', '小王', '2016-04-07 15:26:14', '4'), ('5', '小明', '2016-04-11 15:26:40', '4'), ('6', '小明', '2016-04-04 15:26:54', '2');
commit;
set foreign_key_checks = 1;
导入成功后,执行以下 sql 语句:
mysql> set names utf8;
mysql> select * from employee_tbl;
结果如下:
---- -------- --------------------- --------
| id | name | date | singin |
---- -------- --------------------- --------
| 1 | 小明 | 2016-04-22 15:25:33 | 1 |
| 2 | 小王 | 2016-04-20 15:25:47 | 3 |
| 3 | 小丽 | 2016-04-19 15:26:02 | 2 |
| 4 | 小王 | 2016-04-07 15:26:14 | 4 |
| 5 | 小明 | 2016-04-11 15:26:40 | 4 |
| 6 | 小明 | 2016-04-04 15:26:54 | 2 |
---- -------- --------------------- --------
6 rows in set (0.00 sec)
接下来我们使用 group by 语句 将数据表按名字进行分组,并统计每个人有多少条记录:
mysql> select name, count(*) from employee_tbl group by name;
结果如下
-------- ----------
| name | count(*) |
-------- ----------
| 小丽 | 1 |
| 小明 | 3 |
| 小王 | 2 |
-------- ----------
3 rows in set (0.01 sec)
with rollup 可以实现在分组统计数据基础上再进行相同的统计(sum,avg,count…)。
例如我们将以上的数据表按名字进行分组,再统计每个人登录的次数:
mysql> select name, sum(singin) as singin_count from employee_tbl group by name with rollup;
结果如下:
-------- --------------
| name | singin_count |
-------- --------------
| 小丽 | 2 |
| 小明 | 7 |
| 小王 | 7 |
| null | 16 |
-------- --------------
4 rows in set (0.00 sec)
其中记录 null 表示所有人的登录次数。
我们可以使用 coalesce 来设置一个可以取代 null 的名称,coalesce 语法:
select coalesce(a,b,c);
参数说明:如果a==null,则选择b;如果b==null,则选择c;如果a!=null,则选择a;如果a b c 都为null ,则返回为null(没意义)。
以下实例中如果名字为空我们使用总数代替:
mysql> select coalesce(name, '总数'), sum(singin) as singin_count from employee_tbl group by name with rollup;
结果如下:
-------------------------- --------------
| coalesce(name, '总数') | singin_count |
-------------------------- --------------
| 小丽 | 2 |
| 小明 | 7 |
| 小王 | 7 |
| 总数 | 16 |
-------------------------- --------------
4 rows in set (0.01 sec)