关键语法
GROUP BY
根据给定数据列的每个成员对查询结果分组统计,最终得到分组汇总表
- 满足 : select子句中对列名必须为分组列或者列函数
- 列函数对于group by子句定义的每个组返回一个结果
案例:
表结构:
一张表:
-- 查询所有同学的学号、选课数、总成绩
select tudent_id,count(course_id),sum(score)
from score
group by tudent_id多张表:
-- 查询所有同学的学号、姓名、选课数、总成绩
select s.tudent_id,stu.student_name,count(s.course_id),sum(s.score)
from
score s
student stu
where
s.student_id = stu.student_id
group by s.tudent_idHAVING
-
通常与GROUP BY子句一起使用
-
WHERE过滤行,HAVING过滤组
-
出现在同一sql中的顺序:WHERE→GROUP BY→HAVING
-
如果省略group by,having子句的作用和where一样
案例:
-- 查询平均成绩大于60分的同学的学号和平均成绩
select student_id,avg(score)
from score
group by student_id
having avg(score)>60-- 查询没有学全所有课的同学的学号、姓名
select stu.student_id,stu.name
from
student stu
score s
where
stu.student_id = s.student_id
group by s.student_id
having count(*) <
(
select count(*) from course
)统计相关
COUNT、SUM、MAX、MIN、AVG