题解 | #根据指定记录是否存在输出不同情况#

根据指定记录是否存在输出不同情况

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

1. 每个用户试卷未完成数和未完成率(保留3位小数)

第一种:思路清晰版

select 
    uid,        #包含有、无作答记录的用户,无作答记录的三个指标均设为0
    ifnull(incomplete_cnt, 0) incomplete_cnt, 
    ifnull(did_cnt, 0) did_cnt,
    ifnull(incomplete_rate, 0.000) incomplete_rate, 
    level
from user_info a 
left join (
    select 
        uid,    #均为有作答记录的用户
        sum(if(submit_time is null, 1, 0)) incomplete_cnt,
        count(start_time) did_cnt,
        round(sum(if(submit_time is null, 1, 0))/count(start_time),3) incomplete_rate
    from exam_record
    group by uid    
)t using(uid) 

第二种:缩减版

select 
    uid, level,
    count(start_time) - count(submit_time) incomplete_cnt,  #此时sum(if(submit_time is null, 1, 0))不行,因为合并了user_info和exam_record,可能存在无作答记录的用户
    count(submit_time) complete_cnt,
    count(start_time) did_cnt,
    round(if(count(start_time)!=0, (count(start_time)-count(submit_time))/count(start_time), 0), 3) incomplete_rate    #未作答过的填0.000
from user_info a left join exam_record b using(uid)
group by uid 

2.将上述结果作为临时表,用where (not) exists和UNION 合并两种情况的查询结果。

# 所有用户(包括有无作答记录的)的未完成数、完成数、作答数。有作答记录但未完成数为0的did_cnt>0,无作答记录的did_cnt为0
with t as (
    select 
        uid, level,
        count(start_time) - count(submit_time) incomplete_cnt,  #此时sum(if(submit_time is null, 1, 0))不行,因为合并了user_info和exam_record,可能存在无作答记录的用户
        count(submit_time) complete_cnt,
        count(start_time) did_cnt,
        round(if(count(start_time)!=0, (count(start_time)-count(submit_time))/count(start_time), 0), 3) incomplete_rate    #未作答过的填0.000
    from user_info a left join exam_record b using(uid)
    group by uid 
)

select uid, incomplete_cnt, incomplete_rate from t
where exists (select uid from t where incomplete_cnt>2 and level=0)
and level=0     #第一种情况,输出每个0级用户的试卷未完成数和未完成率
UNION 
select uid, incomplete_cnt, incomplete_rate from t
where not exists (select uid from t where incomplete_cnt>2 and level=0)
and did_cnt>0   #第二种情况,输出所有有作答记录的用户的这两个指标
order by incomplete_rate

全部评论

相关推荐

03-23 15:00
已编辑
厦门大学 Java
xiaowl:你这个简历的问题是对于技术点、项目的描述,都是描述action的,对于面试官而言,仅能知道你干了什么,无法判断你为什么这么干,干的好不好。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务