题目初步分析:

  1. 得出①‘复旦大学’、②‘每位用户’、③‘8月份’、④‘练题总数’、⑤‘答对的题目数’
  2. 限定条件:university='复旦大学',month(date)=8(8月份)
  3. 分组:每位复旦大学的用户(此处用device_id进行分组),group by device_id
  4. 难点:没有在八月份答题的用户也要统计,并且得出结果为0

解题思路:

  1. 需要对两个表格(user_profile和question_practice_detail) 进行联结,由于我们需要筛选出所有用户的答题记录,包括那些没有答过一次题的用户,因此这里选用left join,显示全部user_profile对应的答题信息(没有则为NULL)
  2. 统计每位用户的答题总数以及答对的数量,由于还需要筛选出没有在8月份答题的用户,并且显示为0,因此这里可使用sum(case when),并且在条件内直接进行月份的筛选,而不放在where中——sum(case when month(date)=8 and question_id is not null then 1 else 0 end)——当答题月份为8且答题记录不为NULL,则为1,其他均为0,答对的数量统计同理——(sum(case when month(date)=8 and result = 'right' then 1 else 0 end))
  3. 需要留意联结的键,要用device_id 而不是id,由于是每位用户的答题数据汇总,因此要用group by device_id

完整代码

select t1.device_id,
t1.university,
sum(case when month(t2.date) = 8 and t2.question_id is not null then 1 else 0 end) as question_cnt ,
sum(case when month(t2.date) = 8 and t2.result = 'right' then 1 else 0 end) as right_question_cnt
from user_profile t1
left join question_practice_detail t2 
on t1.device_id=t2.device_id 
where t1.university = '复旦大学' 
group by t1.device_id