MySQL-DQL-聚合函数笔记实例
#创建emp2表
create table emp2
(
id int comment '编号',
workno varchar(10) comment '工号',
name varchar(5) comment '姓名',
gender char(1) comment '性别',
age tinyint unsigned comment '年龄',
idcard char(18) comment '身份证号',
workaddress varchar(50) comment '工作地址',
entrydate date comment '入职时间'
) comment '员工信息表';
#向表中添加数据
insert into emp2(id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (1, '1', '嫦娥', '女', 30, '123456789012345678', '北京', '2000-01-01'),
(2, '2', '张飞', '男', 18, '123456789012345670', '北京', '2005-09-01'),
(3, '3', '李坤', '女', 38, '123456789012345670', '上海', '2005-08-01'),
(4, '4', '赵路', '女', 18, '123456789012345670', '北京', '2009-12-01'),
(5, '5', '小果', '女', 16, '123456789012345678', '上海', '2007-07-01'),
(6, '6', '杨过', '男', 28, '12345678901234567X', '北京', '2006-01-01'),
(7, '7', '范为', '男', 40, '123456789012345670', '北京', '2005-05-01'),
(8, '8', '卢子侧', '男', 38, '123456789012345670', '天津', '2015-05-01'),
(9, '9', '李凉凉', '女', 45, '123456789012345678', '北京', '2010-04-01'),
(10, '10', '陈友谅', '男', 53, '123456789012345670', '上海', '2011-01-01'),
(11, '11', '张士诚', '男', 55, '123456789012345670', '江苏', '2015-05-01'),
(12, '12', '常遇春', '男', 32, '123456789012345670', '北京', '2004-02-01'),
(13, '13', '张无几', '男', 108, '123456789012345678', '江苏', '2020-11-01'),
(14, '14', '女作家', '女', 65, '123456789012345670', '西安', '2019-05-01'),
(15, '15', '胡时', '男', 70, null, '西安', '2018-04-01'),
(16, '16', '周熟人', '男', 28, null, '河南', '2022-06-01'),
(17, '17', '王字清', '男', 24, null, '河南', '2022-06-01'),
(18, '18', '凤城表', '男',30, null, '河南', '2022-06-01'),
(19, '19', '卢书杰', '男', 31, null, '河南', '2022-06-01'),
(20, '20', '狗证', '男', 26, null, '河南', '2022-06-01');
#聚合函数
##1.统计该企业员工数量
select count(*) from emp2;#20
select count(id)from emp2;#20
select count(idcard)from emp2;#14,注意:null值不参与所有的聚合函数运算。
##2.统计该企业员工的平均年龄
select avg(age) from emp2;#38.65岁,20人的平均年龄
##3.统计改企业员工的最大年龄
select max(age)from emp2;#108
##4.统计该企业员工的最小年龄
select min(age)from emp2;#16
##5.统计河南地区员工的年龄之和
select sum(age)from emp2 where workaddress='河南';