题目解析:
题目要求的是保留2021年有试卷完成记录的用户,故以表examination_record作为主表
条件:
(1)试卷:高难度,类别:SOL difficulty='hard' and tag='SQL' (来自于表:examination_info)
(2)用户级别:7级 level=7 (来自于表:user_info)
(3) 在条件1,2的基础上,用户得分平均分80分,则需先根据用户id分组后,计算得分平均值>80
group by er.uid
having avg(score)>80
由条件1、2、3筛选出符合题意的用户id
相关语句如下:
where er.uid in (
select er.uid from exam_record er left join examination_info ei on er.exam_id=ei.exam_id left join user_info ui on er.uid=ui.uid
where difficulty='hard' and tag='SQL'and level=7
group by er.uid
having avg(score)>80
)
题目求解:符合要求的用户2021年试卷总完成次数和题目总练习数
要求:
(1)完成时间是2021年,有试卷完成记录,表示该用户是否存在题目练习记录均可 则 year(er.submit_time)=2021
(2)结果按照试卷完成次数升序,题目练习数降序:order by exam_cnt,question_cnt desc;
完整语句如下:
select er.uid,count(distinct exam_id) exam_cnt,count(distinct if(year(pr.submit_time)=2021,pr.submit_time,null)) question_cnt
from
exam_record er left join practice_record pr on er.uid=pr.uid
where er.uid in (
select er.uid from exam_record er left join examination_info ei on er.exam_id=ei.exam_id left join user_info ui on er.uid=ui.uid
where difficulty='hard' and tag='SQL'and level=7
group by er.uid
having avg(score)>80
)
and
year(er.submit_time)=2021
group by er.uid
order by exam_cnt,question_cnt desc;
(虽然运行出来没问题,但是老实说我自己的思考觉得使用distinct其实还是存在一些问题的,但我目前暂时也没想好在我现在的基础上,要怎么调整才更符合题意。。暂时先这样吧,要是后续想出来更好的解答再补充)
运行结果
京公网安备 11010502036488号