题解 | #第二快/慢用时之差大于试卷时长一半的试卷#(个人废话很多,而且不是最优,只是自己的一些思路)

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

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

算是写给自己的题解吧。(占用牛客资源了,很自私。)但如果你也正好有相同的想法或者错误,那实在是卜数只偶!

我*、一开始看到有两个表,并且看到题目要求的东西只在一个表格里面,我就想到用子查询,就是先在一个表中求出时差大于时长一半的试卷id 再where in就好了。

后来写的过程中走了很多弯路,也犯了很多错误,但是好在我用的是子查询,反而方便了我逐项查询错误的位置(233333~~)

我觉得掌握了思路的话,一步步拆解,先从简单再到难,再拼接还是很容易写出来的,所以我打算讲讲自己犯错的地方。

以下是正确通过了的代码(错误的代码我放在了后面)

select exam_id,duration,release_time
from examination_info
where exam_id in (select exam_id
                  from  (
                        select exam_id,
                        timestampdiff(second,start_time,submit_time) as ys,
                        row_number() over (partition by exam_id order by timestampdiff(second,start_time,submit_time)) r1,
                        row_number() over (partition by exam_id order by timestampdiff(second,start_time,submit_time) desc) r2
                        from exam_record
                        where submit_time is not null
                        ) b
                   group by exam_id
                   having sum(case when r1 = 2 then -ys 
                                  when r2 = 2 then ys 
                                  else 0 end) > duration*30
                  )
order by exam_id desc

最开始写的代码

我当时的思路是没有错的,看最外面的查询框架是可以看出来的。错就错在了子查询里面,我当时看过些正确的题解,我觉得写两行rank太长太麻烦了,看着都累,干脆写一行偷懒算了,结果发现想要做出一个减法出来是相当的难,我想了很久都没能想出来,想过用 union 来连表,也想过用子子子查询来解决。但是发现都无法跳开如何同时取出rank = 2 和rank = ‘-2’的问题,只能添加一列在旁边,当时想的时间长了,脑子钝了,都还在想自己好像只会如何造行,不懂如何造列,更是可笑至极,现在想来造列不就多个select 后面的逗号罢了。

还有个错误是 11行里面的group by是没必要了的,我最后一直错在这个地方,好在子查询帮了我个大忙,很轻松我就找到了。思考之后,发现是rank里面已经包含了分类了。。。

也并不是自己完全做出来的,很多地方都参考了题解的代码,2021/10/23号那天发的那个,就是看的他的怎么对两段数据相加减,我觉得思路很棒!!

select exam_id,duration,release_time
from examination_info
where exam_id in (select exam_id,ys as dsd2,0 as 
                  from (select exam_id,
                        timestampdiff(second,start_time,submit_time) as ys,
                        row_number() over (partition by exam_id order by timestampdiff(second,start_time,submit_time)) 
                        from exam_record
                        where submit_time is not null
                        group by exam_id)
                   where ranking = count(ys) -1
                   group by exam_id
                   union all
                  )
order by exam_id desc
全部评论

相关推荐

头像
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务