基于hive表小练习-CSDN博客的拓展
-- 1. 查询没有参与任意一门考试的学生姓名
LEFT JOIN操作时,数据库系统会从左表(即LEFT JOIN关键字左边的表)返回所有的行,
即使在右表(即LEFT JOIN关键字右边的表)中没有匹配的行。
对于那些在右表中没有匹配项的左表行,结果集中的右表列将填充为NULL值。
因为分数表中的学生id不全
左表t1 学生表 右表t2 分数表
select t1.stu_name
from school.student_info t1
left join school.score_info t2
on t1.stu_id=t2.stu_id
where t2.stu_id is null;
-- 3. 查询每门课程的平均成绩,结果按平均成绩升序排序,平均成绩相同时,按课程号降序排列
select course_id,avg(score) as average_score from school.score_info group by course_id order by average_score asc,course_id desc;
4. 查询所有课程成绩均小于60分的学生的学号、姓名
--1.查询课程分数小于60分的学生id
select stu_id from school.score_info where score< 60;
--2.与学生表连接 查询学生的学号姓名
select t1.stu_id,t1.stu_name from school.student_info t1
inner join (select distinct stu_id from school.score_info where score< 60) t2
on t1.stu_id=t2.stu_id;
5. 查询有两门以上的课程不及格的同学的姓名及其平均成绩
--1.查询两门以上课程不及格的学生id和平均成绩
select stu_id,avg(score) as average_score from school.score_info group by stu_id having count(case when score<60 then 1 else 0 end)>=2;
SUM(CASE...WHEN...THEN...ELSE...END)
构造,它会对每条记录根据条件进行评估:如果成绩小于60,则计为1;否则,计为0。然后,SUM
函数会累加每组(每个学生)中所有计为1的值,如果这个总和大于等于2,说明该学生有两门或以上的课程不及格。
这里的结果集是
--2.与学生表连接 查询学生的学号姓名
select t1.stu_id,t1.stu_name from school.student_info t1
inner join (select distinct stu_id from school.score_info where score< 60) t2
on t1.stu_id=t2.stu_id;
-- 6. 查询平均成绩大于85的所有学生的学号、姓名和平均成绩
--1.查询平均成绩大于85分的学生学号
select stu_id,avg(score) as average_score from school.score_info group by stu_id having avg(score)>85;
--2.与学生表链接,查询学生姓名
select t1.stu_id,t1.stu_name,t2.average_score from school.student_info t1
inner join (select stu_id,avg(score) as average_score from school.score_info group by stu_id having avg(score)>85) t2
on t1.stu_id = t2.stu_id;
7. 查询出每门课程的及格人数和不及格人数
--1.每门课程:按课程分组 查询每门课程id的及格人数
select course_id,sum(case when score>=60 then 1 else 0 end) as pass_count,sum(case when score<60 then 1 else 0 end) as fail_count from school.score_info group by course_id;
结果集
--2.与课程表连接,查询对应的课程名
select t1.course_id,t1.course_name,t2.pass_count,t2.fail_count from school.course_info t1
inner join (select course_id,sum(case when score>=60 then 1 else 0 end) as pass_count,sum(case when score<60 then 1 else 0 end) as fail_count from school.score_info group by course_id) t2
on t1.course_id = t2.course_id
;
- 8. 课程编号为"01"且课程分数小于60,按分数降序排列的学生信息
--1.从分数表中查找学生id
select stu_id from school.score_info where course_id='01' and score <60;
--2.与学生表连接
select * from school.student_info t1
inner join (select stu_id,score from school.score_info where course_id='01' and score <60) t2
on t1.stu_id = t2.stu_id
order by t2.score
;