聚合函数
MYSQL 中内置了 5 种聚合函数,分别是: SUM 、 MAX 、 MIN 、 AVG 、 COUNT 。
sum : 求和
select sum(列) from table_name [其他子句];
select student_id,sum(score) from score group by student_id;

max : 求最大值
select max(列) from table_name [其他子句];
select max(score) from score where course_id=1;

min : 求最小值
select min(列) from table_name [其他子句];
select min(score) from score where course_id=1;

avg : 求平均值
select avg(列) from table_name [其他子句];
select student_id,avg(score) from score group by student_id;

count : 求数量
select count(列) from table_name [其他子句];
select count(*) from course;

group by
group by 是对数据进行分组,分组时,表中有相同值的分为一组。分组后可以进行聚合查询。
group by 分组后的查询中, select 的列不能出现除了 group by 分组条件以及聚合函数外的其他列。
select 列1, 列2, (聚合函数) from table_name group by 列1, 列2;
select s.id,s.name,sum(score) from student s,score sc where s.id=sc.student_id group by s.id,s.name;

having
having 是对 group by 分组后的结果集进行筛选。
select 列1, 列2, (聚合函数) from table_name group by 列1, 列2 having分组后条件;
select s.id,s.name,sum(score) from student s,score sc where s.id=sc.student_id group by s.id,s.name having sum(score)>180;

MySQL支持SUM、MAX、MIN、AVG、COUNT等5种聚合函数,用于对数据进行求和、最大值、最小值、平均值和计数操作。GROUPBY用于数据分组,HAVING则在分组后进行筛选。例如,可以使用GROUPBY结合聚合函数分析学生分数,或者使用HAVING找出总分超过180的学生。
1826

被折叠的 条评论
为什么被折叠?



