题解 | #第二快/慢用时之差大于试卷时长一半的试卷#

第二快/慢用时之差大于试卷时长一半的试卷

https://www.nowcoder.com/practice/b1e2864271c14b63b0df9fc08b559166

终于算是自己做出一道比较麻烦的题,这题其实不算特别难,主要就是理清逻辑,无限套娃,在这里分享一下自己的思路,虽然代码比较长,但绝对好理解。

第1步:先用from子查询+降序排序窗口函数,制作包含不同试卷ID及其对应被作答用时第二慢的所花的时间的表a
(select exam_id,desc_time,desc_ranking from
(select exam_id,timestampdiff(second,start_time,submit_time) desc_time,row_number()over(partition by exam_id order by timestampdiff(second,start_time,submit_time) desc) desc_ranking from exam_record
where submit_time is not null) t1
where desc_ranking = 2) a
(注意要限制submit_time is not null,不然就会有null值进入所花时间的排序!!!
第2步:用跟第一步同样的方法,将降序改为升序,制作包含不同试卷ID及其对应被作答用时第二快的所花的时间的表b
(select exam_id,asc_time,asc_ranking from
(select exam_id,timestampdiff(second,start_time,submit_time) asc_time,row_number()over(partition by exam_id order by timestampdiff(second,start_time,submit_time) asc) asc_ranking from exam_record
where submit_time is not null) t2
where asc_ranking = 2) b

第3步:将表a的exam_id和表b的exam_id作为连接键,将表a和表b连接起来,制作包含不同试卷ID及其对应第二快和第二慢用时之差的表c
(select a.exam_id exam_id,desc_time - asc_time time from
(select exam_id,desc_time,desc_ranking from
(select exam_id,timestampdiff(second,start_time,submit_time) desc_time,row_number()over(partition by exam_id order by timestampdiff(second,start_time,submit_time) desc) desc_ranking from exam_record
where submit_time is not null) t1
where desc_ranking = 2) a
join 
(select exam_id,asc_time,asc_ranking from
(select exam_id,timestampdiff(second,start_time,submit_time) asc_time,row_number()over(partition by exam_id order by timestampdiff(second,start_time,submit_time) asc) asc_ranking from exam_record
where submit_time is not null) t2
where asc_ranking = 2) b
on a.exam_id = b.exam_id) c

最后一步:将表c的exam_id和原表examination_infoexam_id作为连接键,将表c和表examination_info连接起来,添加限制条件后得到我们最终的运行代码
select c.exam_id,duration,release_time from 
(select a.exam_id exam_id,desc_time - asc_time time from
(select exam_id,desc_time,desc_ranking from
(select exam_id,timestampdiff(second,start_time,submit_time) desc_time,row_number()over(partition by exam_id order by timestampdiff(second,start_time,submit_time) desc) desc_ranking from exam_record
where submit_time is not null) t1
where desc_ranking = 2) a
join 
(select exam_id,asc_time,asc_ranking from
(select exam_id,timestampdiff(second,start_time,submit_time) asc_time,row_number()over(partition by exam_id order by timestampdiff(second,start_time,submit_time) asc) asc_ranking from exam_record
where submit_time is not null) t2
where asc_ranking = 2) b
on a.exam_id = b.exam_id) c
left join examination_info on c.exam_id = examination_info.exam_id
where time > duration*60/2
order by c.exam_id desc



全部评论

相关推荐

神哥不得了:神哥来啦~自我评价和校园经历的话可以直接删了,从大厂暑期的话应该没有什么太多问题,应该是能拿到很多大厂面试机会的,就是在面试的时候表示的好一点就行,可以在面试前先把高频top 50的八股多巩固几遍,千万不要看那些假高频八股,这两个项目的话问题不是很大,应该能够帮你找到大厂实习的,算法的话一定要刷起来,因为大厂有些还是比较看重算法的
点赞 评论 收藏
分享
03-02 10:51
邵阳学院 Java
红鲤鱼与绿鲤鱼i:看了你的头像不像找工作,像在找妹子
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-27 17:55
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务