MySQL数据库系统select语句相关练习

(1) 在students表中,查询年龄大于25岁,且为男性的同学的名字和年龄
select name,age from students where age >25;

(2) 以ClassID为分组依据,显示每组的平均年龄
select classid,avg(age) from students group by classid;

(3) 显示第2题中平均年龄大于30的分组及平均年龄
select classid,avg(age) from students group by classid having avg(age)>30;

(4) 显示以L开头的名字的同学的信息
select * from students where name like ‘l%’;

(5) 显示TeacherID非空的同学的相关信息
select * from students where teacherid is not null;

(6) 以年龄排序后,显示年龄最大的前10位同学的信息
select * from students order by age desc limit 10;

(7) 查询年龄大于等于20岁,小于等于25岁的同学的信息
select * from students where age between 20 and 25;

1、以ClassID分组,显示每班的同学的人数
select class,count(name) from classes inner join students on classes.classid=students.classid group by students.classid;

2、以Gender分组,显示其年龄之和
select gender,sum(age) from students group by gender;

3、以ClassID分组,显示其平均年龄大于25的班级
select class,avg(age) from classes inner join students on classes.classid=students.classid group by students.classid having avg(age)>25;

4、以Gender分组,显示各组中年龄大于25的学员的年龄之和
select s.gender,sum(s.age) from (select gender,age from students where age>25) as s group by s.gender ;

5、显示前5位同学的姓名、课程及成绩
select s.name,courses.course,s.score from (select scores.stuid,students.name,courseid,score from scores left join students on scores.stuid=students.stuid having scores.stuid<=5) as s left join courses on s.courseid=courses.courseid;
6、显示其成绩高于80的同学的名称及课程
select s.name,courses.course,s.score from (select scores.stuid,students.name,courseid,score from scores left join students on scores.stuid=students.stuid) as s left join courses on s.courseid=courses.courseid having s.score>80;

7、取每位同学各门课的平均成绩,显示成绩前三名的同学的姓名和平均成绩
select ss.name, avg(ss.score) from (select s.name,courses.course,s.score from (select scores.stuid,students.name,courseid,score from scores left join students on scores.stuid=students.stuid) as s left join courses on s.courseid=courses.courseid) as ss group by ss.name order by avg(ss.score) desc limit 3;

8、显示每门课程课程名称及学习了这门课的同学的个数
select courses.course,count(name) from students left join courses on students.classid=courses.courseid group by students.classid;

9、显示其年龄大于平均年龄的同学的名字
select name,age from students where age>(select avg(age) from students);

10、显示其学习的课程为第1、2,4或第7门课的同学的名字
select name,classid from students where classid in (1,2,4,7);

11、显示其成员数最少为3个的班级的同学中年龄大于同班同学平均年龄的同学
select student.name,student.age,student.classid,second.avg_age from (select students.name as name ,students.age as age,students.classid as classid from students left join (select count(name) as num,classid as classid from students group by classid having num>=3) as first on first.classid=students.classid) as student,(select avg(age) as avg_age,classid as classid from students group by classid) as second where student.age>second.avg_age and student.classid=second.classid;

12、统计各班级中年龄大于全校同学平均年龄的同学
select name,age from students group by classid having age>(select avg(age) from students);

你可能感兴趣的:(Linux练习)