一、常用聚合函数
1.
函数 | 意义 |
---|---|
sum() | 总合 |
avg() | 平均 |
max() | 最大值 |
min() | 最小值 |
count()计数 | 意义 |
---|---|
count(student) | 记录学生的个数null值不计数 |
count(1) | 计算索引数量 |
count(*) | 计算所有数据数量 |
二、案例:分组过滤查询.
查询不同课程的学生的成绩的平均分,最高分,最低分,平均分要大于60分,
核心通过不同的课程进行分组,( WHERE 不能和 GROUP BY 连用,使用 HAVING 代替)
1. 建表.
1.建表
CREATE TABLE `studentexam` (
`name` varchar(100) DEFAULT NULL COMMENT '学生姓名',
`testSubject` varchar(20) DEFAULT NULL COMMENT '考试科目',
`score` varchar(2) DEFAULT NULL COMMENT '分数等级',
`numberScore` int(11) DEFAULT NULL COMMENT '分数数字'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.插入数据后:(你也可以随机插入数据)
2. 查询
(1)第一次尝试。
SELECT
`studentexam`.`testSubject` AS 科目,
AVG(`studentexam`.`numberScore`)AS 平均分,
MAX(`studentexam`.`numberScore`) AS 最高分,
MIN(`studentexam`.`numberScore`) AS 最低分
FROM `studentexam`
效果:
结论:只有数学一门课,这是因为没有分组的缘故。(2)我们是用group by 分组
(2)第二次尝试,使用group by 分组,
SELECT
`studentexam`.`testSubject` AS 科目,
AVG(`studentexam`.`numberScore`)AS 平均分,
MAX(`studentexam`.`numberScore`) AS 最高分,
MIN(`studentexam`.`numberScore`) AS 最低分
FROM `studentexam`
GROUP BY 科目
效果:
结论:分组成功,下面我们新的要求查询平均分及格的以上条件。
(3)在(2) 的基础查询平均分及格的科目,
SELECT
`studentexam`.`testSubject` AS 科目,
AVG(`studentexam`.`numberScore`)AS 平均分,
MAX(`studentexam`.`numberScore`) AS 最高分,
MIN(`studentexam`.`numberScore`) AS 最低分
FROM `studentexam`
WHERE `studentexam`.`numberScore` >= 60
GROUP BY 科目
效果:报错
where 的地方错了.
原因是where不能和 group by 连用,使用 having 代替.(4)
(4) 在(3)的基础上使用 having 替代 where (注意select 语法)
(重点)select 语法
select
[all|distanct] -- 1.字段
from
[table1|table1,table2] -- 2.表
inner join [table_2] ---3.联合查询
on [联合查询条件] --
where... -- 3.where 满足条件
group by [...] -- 4.分组
having [...] -- 分组的次要条件
order by [表.字段 desc|ASC] -- 5.排序
limit [开始查询的行数],[查询的行数];
-- 6.分页.
having 在 group by 的后面.
SELECT
`studentexam`.`testSubject` AS 科目,
AVG(`studentexam`.`numberScore`)AS 平均分,
MAX(`studentexam`.`numberScore`) AS 最高分,
MIN(`studentexam`.`numberScore`) AS 最低分
FROM `studentexam`
GROUP BY 科目
HAVING 平均分 > 60
效果:
结论:查询成功,having 在 group by 的后面,使用group by 分组》