闲来没事,谢谢sql玩

超经典SQL练习题,做完这些你的SQL就过关了

原网址:https://blog.csdn.net/flycat296/article/details/63681089

# 1. 查询" 01 "课程比" 02 "课程成绩高的学生的信息及课程分数
select * from (select * from SC where c = '01') A
left join (select * from SC where c = '02') B
on A.s = B.s
where A.score > B.score;

# 2. 查询平均成绩大于等于 60 分的同学的学生编号和学生姓名和平均成绩
select sum(A.score), count(*), sum(A.score)/count(*) as pingjun from SC A
left join Student B
on A.S = B.S
group by B.S;


# 4. 查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为 null )
select A.S, A.Sname,count(DISTINCT B.C) ,sum(B.score) from Student A 
left join SC B
on A.S = B.S
GROUP BY A.s;


#6. 查询学过「张三」老师授课的同学的信息 
select * from SC B 
where B.C in( select A.C from Course A where A.T = '02');

select * from SC B 
RIGHT JOIN (select A.C from Course A where A.T = '02') C
on B.C = C.C;

# 7. 查询没有学全所有课程的同学的信息 ( having 字句, having 是筛选组  而where是筛选记录,用having就一定要和group by连用。)
select * from (select A.S , count(*) as n from SC A group by A.S ) B
where B.n < 3;
# having
select A.S , count(*) as n from SC A group by A.S Having count(n) < 3

#8 查询至少有一门课与学号为" 01 "的同学所学相同的同学的信息 
select * from SC A
where A.C in ( select C from SC B where B.S='01') and A.S <> '01'
group by A.S


#9 查询和" 01 "号的同学学习的课程完全相同的其他同学的信息 
select * from (select s,group_concat(c order by c) gc from SC group by s) a 
join Student s on a.s=s.s where a.gc=(select group_concat(c) from SC where s=6) 

#-11.查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩   
select C.S,AVG(score)  from  SC C where C.S in (select A.s from SC A where A.score< 60 
GROUP BY S
HAVING count(*) >2) 
GROUP BY C.S


-- 13. (静态写法)按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
select S, 
max(case C when '01' then score else 0 end) as 课程一,
max(case C when '02' then score else 0 end) as 课程二,
max(case C when '03' then score else 0 end) as 课程三, AVG(A.score) 平均分 from SC A 
GROUP BY A.S ORDER BY 平均分 desc
   
-- 14. 查询各科成绩最高分、最低分和平均分:
-- 以如下形式显示:课程 ID,课程 name,最高分,最低分,平均分,及格率,中等率,优良率,优秀率
 -- 及格为>=60,中等为:70-80,优良为:80-90,优秀为:>=90
-- 要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列 
select A.C as 课程ID,B.Came 课程名称, count(*) 选修人数,
sum(case  when score>=60 then 1 else 0 END)/count(*) as 及格率, 
sum(case  when score>=70 AND score< 80 then 1 else 0 END)/count(*) as 中等率,
sum(case  when score>=80 AND score< 90 then 1 else 0 END)/count(*) as 优良率, 
sum(case  when score>=90  then 1 else 0 END)/count(*) as 优秀率
from SC A 
JOIN Course B  on A.C = B.C  
group by A.C
ORDER BY count(*) desc, A.C desc;
 
-- 15. 按各科成绩进行排序,并显示排名, Score 重复时保留名次空缺
-- 15.2  按各科成绩进行排序,并显示排名, Score 重复时合并名次
-- 参考:https://blog.csdn.net/a9925/article/details/76804951
select @rownum := @rownum + 1  无并列排序,

score from SC ,(SELECT @rownum := 0) t   
where c = 01 
ORDER BY score desc; 

-- 18 查询各科成绩前三名的记录 (用到了sql_server的分区函数)
分区函数









猜你喜欢

转载自blog.csdn.net/sinat_41075535/article/details/80069800