在分组的列上我们可以使用 count, sum, avg,等函数。
group by 语法
select column_name,function(column_name)from table_name
where column_name operator value
group by column_name;
实例演示
本章节实例使用到了以下表结构及数据,使用前我们可以先将以下数据导入数据库中。
mariadb [runoob]> set names utf8;query ok, 0 rows affected (0.00 sec)
mariadb [runoob]> set foreign_key_checks = 0;query ok, 0 rows affected (0.00 sec)
mariadb [runoob]> drop table if exists `employee_tbl`;query ok, 0 rows affected, 1 warning (0.00 sec)mariadb [runoob]> 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;query ok, 0 rows affected (0.04 sec)
mariadb [runoob]> begin;query ok, 0 rows affected (0.00 sec)
mariadb [runoob]> insert into employee_tbl values ('1', 'aa', '2016-04-22 15:25:33', '1'), ('2', 'bb', '2016-04-20 15:25:47', '3'), ('3', 'cc', '2016-04-19 15:26:02', '2'), ('4', 'bb', '2016-04-07 15:26:14', '4'), ('5', 'aa', '2016-04-11 15:26:40', '4'), ('6', 'aa', '2016-04-04 15:26:54', '2');query ok, 6 rows affected, 6 warnings (0.00 sec)
records: 6 duplicates: 0 warnings: 6
mariadb [runoob]> commit;query ok, 0 rows affected (0.00 sec)
mariadb [runoob]> set foreign_key_checks = 1;query ok, 0 rows affected (0.00 sec)
导入成功后,执行以下 sql 语句:
mariadb [runoob]> select * from employee_tbl;+----+------+---------------------+--------+
| id | name | date | singin |
+----+------+---------------------+--------+
| 1 | aa | 2016-04-22 15:25:33 | 1 |
| 2 | bb | 2016-04-20 15:25:47 | 3 |
| 3 | cc | 2016-04-19 15:26:02 | 2 |
| 4 | bb | 2016-04-07 15:26:14 | 4 |
| 5 | aa | 2016-04-11 15:26:40 | 4 |
| 6 | aa | 2016-04-04 15:26:54 | 2 |
+----+------+---------------------+--------+
6 rows in set (0.00 sec)
接下来我们使用 group by 语句 将数据表按名字进行分组,并统计每个人有多少条记录:
mariadb [runoob]> select name, count(*) from employee_tbl group by name;+------+----------+
| name | count(*) |
+------+----------+
| aa | 3 |
| bb | 2 |
| cc | 1 |
+------+----------+
3 rows in set (0.00 sec)
使用 with rollup
with rollup 可以实现在分组统计数据基础上再进行相同的统计(sum,avg,count…)。
例如我们将以上的数据表按名字进行分组,再统计每个人登录的次数:
mariadb [runoob]> select name, sum(singin) as singin_count from employee_tbl group by name with rollup;+------+--------------+
| name | singin_count |
+------+--------------+
| aa | 7 |
| bb | 7 |
| cc | 2 |
| null | 16 |
+------+--------------+
4 rows in set (0.00 sec)
其中记录 null 表示所有人的登录次数。
我们可以使用 coalesce 来设置一个可以取代 null 的名称,coalesce 语法:
select coalesce(a,b,c);
参数说明:
如果a!=null,则选择a;
如果a==null,则选择b;
如果b==null,则选择c;
如果a b c 都为null ,则返回为null(没意义)。
以下实例中如果名字为空我们使用总数代替:
mariadb [runoob]> select coalesce(name, '总数'), sum(singin) as singin_count from employee_tbl group by name with rollup;+------------------------+--------------+
| coalesce(name, '总数') | singin_count |
+------------------------+--------------+
| aa | 7 |
| bb | 7 |
| cc | 2 |
| 总数 | 16 |
+------------------------+--------------+
4 rows in set (0.00 sec)
