第五节 SQL分组、多表联接查询
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
--求学生信息表:平均年龄、男生总数、最大,最小年龄、学生人数 selectavg(Age)平均年龄, sum(convert(int,Sex))男生人数,max(age)最大年龄, min(age)最小年龄,count(*)学生人数 from Students --分组统计每种课程的平均分 --通常集合函数配合分组来统计数据的 --在使用聚合函数时,所指定的列必须是聚合函数列、或 --分组所指定的列 select CourseID 课程编号,avg(Score)平均分, Sum(Score)总分,max(Score)最高分,min(Score)最低分, count(*)总人数 from StuMark groupby CourseID --任务:添加部门列,根据部门分组查询最高,最低,平均,总薪水和部门总人数 --多列分组 select CourseID 课程编号,StuID 学员编号, avg(Score)平均分from StuMark groupby CourseID,StuID --分组后筛选信息 select CourseID 课程编号,StuID 学员编号, avg(Score)平均分from StuMark groupby CourseID,StuID havingcount(Score)>1 --多表联接查询 --内联接inner join select Students.SName as姓名, StuMark.Score as成绩from Students innerjoin StuMark on Students.ID=StuMark.StuID --内联接inner join(为表取别名简短sql语句的长度) select s.SName 姓名,m.Score 成绩from Students as s innerjoin StuMark as m on s.ID=m.StuID --内联接:join(单独用join默认为内联接) select s.SName 姓名,m.Score 成绩from Students as s join StuMark as m on s.ID=m.StuID