经典mysql测试题


18--查询各科成绩最高和最低分
select count(course_id),max(num),min(num) from score group by course_id;
19.按各科平均成绩从低到高和及格率的百分数从高到底排序
select course_id,avg(num),sum(case when score.num>60 then 1 else 0 end)/count(count_id)*100% as per from score
group by course_id order by avg(num) asc,per desc;
20.课程平均分从高到低,并且显示任课老师
select course_id,avg(num),teacher.name from score group by course_id order by avg(num) desc
left join teacher on course.teacher_id=teacher.tid
21.查询各科成绩前三名的记录:(不考虑成绩并列情况)
select * from (
select
sid,
student_id,
num,
(select num from scroe as s2 where s2.course_id=s1.course_id order by num desc limit 0,1)as first_num,
(select num from score as s2 where s2.course_id=s1.course_id order by num desc limit 2,1)as second_num
from
score as s1
)as T
where num >=second_num and num<=first_num
22.查询每门课程被选修的学生数
select course_id,count(student_id) from score group by course_id
23.查询出只选修一门课程的学生的的学号和姓名
--自己写的--
select
sid,sname ,
(select student_id from score where count(course_id)=1) as T,

from student where T.student_id=student.sid
--自己写的--
answer trule of 23
(1)先找每个人选了几门课(2)再找出选课数为1的:
select student_id,count(student_id) from score #count(course_id) ----》False,根据后面的分组来写,所以( )内应该写student_id
group by student_id
having count(student_id)=1
!!!!!!! 根据分组完的结果进行操作 时 要使用having
24.查询男生,女生的人数
===============自己写的=======================
select
count('男'),count('女'),

(
(select count('男') from student order by(gender) having gender='男')
(select count('女') from student order by(gender) having gender='女')
)as T

from student
===============自己写的=======================
answer trule of 24
mode1:
select gender,count(gender) from student group by gender
mode2:

select (select count(1) from student where gender='男')as 男,numb
select (select count(1) from student where gender='男')as 女,numb

mode3:
以下是两个分开的表:
(select count(1) from student where gender='男')
(select count(1) from student where gender='女')
mode4:(通过迪卡积):
select * from
(select count(1) from student where gender='男') as table1,
(select count(1) from student where gender='女') as table2

猜你喜欢

转载自www.cnblogs.com/startl/p/12435785.html