【牛客】SQL134 满足条件的用户的试卷完成数和题目练习数

描述

现有用户信息表user_info(uid用户ID,nick_name昵称, achievement成就值, level等级, job职业方向, register_time注册时间):

id uid nick_name achievement level job register_time
1 1001 牛客1号 3100 7 算法 2020-01-01 10:00:00
2 1002 牛客2号 2300 7 算法 2020-01-01 10:00:00
3 1003 牛客3号 2500 7 算法 2020-01-01 10:00:00
4 1004 牛客4号 1200 5 算法 2020-01-01 10:00:00
5 1005 牛客5号 1600 6 C++ 2020-01-01 10:00:00
6 1006 牛客6号 2000 6 C++ 2020-01-01 10:00:00

试卷信息表examination_info(exam_id试卷ID, tag试卷类别, difficulty试卷难度, duration考试时长, release_time发布时间):

id exam_id tag difficulty duration release_time
1 9001 SQL hard 60 2021-09-01 06:00:00
2 9002 C++ hard 60 2021-09-01 06:00:00
3 9003 算法 medium 80 2021-09-01 10:00:00

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

id uid exam_id start_time submit_time score
1 1001 9001 2021-09-01 09:01:01 2021-09-01 09:31:00 81
2 1002 9002 2021-09-01 12:01:01 2021-09-01 12:31:01 81
3 1003 9001 2021-09-01 19:01:01 2021-09-01 19:40:01 86
4 1003 9002 2021-09-01 12:01:01 2021-09-01 12:31:51 89
5 1004 9001 2021-09-01 19:01:01 2021-09-01 19:30:01 85
6 1005 9002 2021-09-01 12:01:01 2021-09-01 12:31:02 85
7 1006 9003 2021-09-07 10:01:01 2021-09-07 10:21:01 84
8 1006 9001 2021-09-07 10:01:01 2021-09-07 10:21:01 80

题目练习记录表practice_record(uid用户ID, question_id题目ID, submit_time提交时间, score得分):

id uid question_id submit_time score
1 1001 8001 2021-08-02 11:41:01 60
2 1002 8001 2021-09-02 19:30:01 50
3 1002 8001 2021-09-02 19:20:01 70
4 1002 8002 2021-09-02 19:38:01 70
5 1004 8001 2021-08-02 19:38:01 70
6 1004 8002 2021-08-02 19:48:01 90
7 1001 8002 2021-08-02 19:38:01 70
8 1004 8002 2021-08-02 19:48:01 90
9 1004 8002 2021-08-02 19:58:01 94
10 1004 8003 2021-08-02 19:38:01 70
11 1004 8003 2021-08-02 19:48:01 90
12 1004 8003 2021-08-01 19:38:01 80

请你找到高难度SQL试卷得分平均值大于80并且是7级的红名大佬,统计他们的2021年试卷总完成次数和题目总练习次数,只保留2021年有试卷完成记录的用户。结果按试卷完成数升序,按题目练习数降序。

示例数据输出如下:

uid exam_cnt question_cnt
1001 1 2
1003 2 0

解释:用户1001、1003、1004、1006满足高难度SQL试卷得分平均值大于80,但只有1001、1003是7级红名大佬;1001完成了1次试卷1001,练习了2次题目;1003完成了2次试卷9001、9002,未练习题目(因此计数为0)

with cte1 as(
    select uid
    from
    exam_record left join examination_info using(exam_id)
    left join user_info using(uid)
    where difficulty='hard' and tag='SQL' and level=7
    group by uid
    having avg(score)>80
),
cte2 as(
    select uid,count(exam_id) as exam_cnt
    from
    cte1 left join  exam_record using(uid)
    where left(submit_time,4)=2021
    group by uid
),
cte3 as(
    select uid,count(question_id) as question_cnt
    from
    cte1 left join practice_record using(uid)
    where date_format(submit_time,'%Y')=2021
    group by uid
)

select uid,exam_cnt,ifnull(question_cnt,0)
from
cte2 left join cte3 using(uid)
order by exam_cnt,question_cnt desc

你可能感兴趣的:(MySQL-刷题,MySQL,数据库)