【牛客】SQL138 连续两次作答试卷的最大时间窗-窗口函数

2024-03-11 9935阅读

描述

有试卷作答记录表exam_record(uid用户ID, exam_id试卷ID, start_time开始作答时间, submit_time交卷时间, score得分):

【牛客】SQL138 连续两次作答试卷的最大时间窗-窗口函数 第1张
()
iduidexam_idstart_timesubmit_timescore
1100690032021-09-07 10:01:012021-09-07 10:21:0284
2100690012021-09-01 12:11:012021-09-01 12:31:0189
3100690022021-09-06 10:01:012021-09-06 10:21:0181
4100590022021-09-05 10:01:012021-09-05 10:21:0181
5100590012021-09-05 10:31:012021-09-05 10:51:018

请计算在2021年至少有两天作答过试卷的人中,计算该年连续两次作答试卷的最大时间窗days_window,那么根据该年的历史规律他在days_window天里平均会做多少套试卷,按最大时间窗和平均做答试卷套数倒序排序。由示例数据结果输出如下:

uiddays_windowavg_exam_cnt
100662.57

解释:用户1006分别在20210901、20210906、20210907作答过3次试卷,连续两次作答最大时间窗为6天(1号到6号),他1号到7号这7天里共做了3张试卷,平均每天3/7=0.428571张,那么6天里平均会做0.428571*6=2.57张试卷(保留两位小数);

【牛客】SQL138 连续两次作答试卷的最大时间窗-窗口函数 第2张
()

用户1005在20210905做了两张试卷,但是只有一天的作答记录,过滤掉。

with cte1 as (
    select
    uid,date_format(start_time,'%Y%m%d') as act_time,
    dense_rank() over(partition by uid order by date_format(start_time,'%Y%m%d') desc) as rnk
    from
    exam_record
    where uid in(
        select uid from exam_record
        where left(start_time,4)=2021
        group by uid
        having count(distinct left(start_time,10))>=2)
    and left(start_time,4)=2021
),
cte2 as (
    select
    uid,count(act_time)/(datediff(max(act_time),min(act_time))+1) as rate
    from cte1 
    group by uid
),
cte3 as (
    select
    a.uid as uid,
    round(max(datediff(a.act_time,b.act_time)+1),2) as days_window
    from
    cte1 a left join cte1 b
    on a.uid=b.uid and a.rnk+1=b.rnk
    group by a.uid
)
select
uid,days_window,round(days_window*rate,2) as avg_exam_cnt
from cte2 left join cte3 using(uid)
order by days_window desc,avg_exam_cnt desc

ps:在做连接查询的时候使用cte2 left join cte3没有问题,使用cte3 left join cte2会报错,有知道这是什么问题的友友可以在评论区留言,感谢😭


    免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

    目录[+]