Mysql数据库查询之分组查询

发布时间 2023-11-14 01:07:06作者: Lzljh

1.分组查询语法:

SELECT 字段 1,字段 2 FROM 表名 where 条件 GROUP BY 分组字段 HAVING 条件 order by;

2. 统计类型:

求平均,求最大,求最小,求和等等

分组查询需要结合分组函数一起完成,常用的分组函数:

COUNT(参数):统计查询语句返回的行数

MAX(参数):求最大

MIN(参数):求最小

AVG(参数):求平均

SUM(参数):求和

3.单列分组查询:

1.根据科目分组,查询每个科目的平均分

select subjectID,avg(exam) as 平均分 form exam group by subjectID;
2.根据班级分组,查询每个班级成绩总数

select Classid,count(*) as 人数 from exam group by classid;
3.根据班级分组,查询每个班级的最低分

select Classid,min(exam) as 成绩 from group by classid order by min(exam) asc;

4.多列分组查询:

1.查询每个班的男生、女生数量

select ClassID as 班级,gender as 性别,count(studentID) as 人数 from student group by ClassID,gender;
2.查询1班2班大于50分的最低成绩

select Classid as 班级,min(exam) from group by Classid having min(exam)>50 order by min(exam) asc;
3.统计除去不及格成绩,平均分在80分以上的人数

select subjectId,avg(exam) as 平均分,count(*) as 人数 from exam where exam>=60 group by subjectId having avg(exam)