1412. 查找成绩处于中游的学生sql

该问题涉及使用SQL查询从Student和Exam表中找出所有在每次测验中得分既非最高也非最低的学生。查询首先通过LEFTJOIN连接两个表,然后排除得分在每个测验的最大值和最小值中的学生,以及从未参加过测验的学生。
摘要由CSDN通过智能技术生成

成绩处于中游的学生是指至少参加了一次测验, 且得分既不是最高分也不是最低分的学生。

写一个 SQL 语句,找出在 所有 测验中都处于中游的学生 (student_id, student_name)。

不要返回从来没有参加过测验的学生。返回结果表按照 student_id 排序。

 

Create table If Not Exists Student (student_id int, student_name varchar(30))

Create table If Not Exists Exam (exam_id int, student_id int, score int)

Truncate table Student

insert into Student (student_id, student_name) values ('1', 'Daniel')

insert into Student (student_id, student_name) values ('2', 'Jade')

insert into Student (student_id, student_name) values ('3', 'Stella')

insert into Student (student_id, student_name) values ('4', 'Jonathan')

insert into Student (student_id, student_name) values ('5', 'Will')

Truncate table Exam

insert into Exam (exam_id, student_id, score) values ('10', '1', '70')

insert into Exam (exam_id, student_id, score) values ('10', '2', '80')

insert into Exam (exam_id, student_id, score) values ('10', '3', '90')

insert into Exam (exam_id, student_id, score) values ('20', '1', '80')

insert into Exam (exam_id, student_id, score) values ('30', '1', '70')

insert into Exam (exam_id, student_id, score) values ('30', '3', '80')

insert into Exam (exam_id, student_id, score) values ('30', '4', '90')

insert into Exam (exam_id, student_id, score) values ('40', '1', '60')

insert into Exam (exam_id, student_id, score) values ('40', '2', '70')

insert into Exam (exam_id, student_id, score) values ('40', '4', '80')

select student_id, student_name 

from Student

where (student_id, student_name) not in (

    select s.student_id, s.student_name

    from Student s left join Exam e on s.student_id = e.student_id

    where (e.exam_id, e.score) in (

        select exam_id, max(score) score

        from Exam

        group by exam_id

        union all

        select exam_id, min(score) score

        from Exam

        group by exam_id

    ) or e.exam_id is null

    group by s.student_id

)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值