题意解读

现在运营想要了解复旦大学的每个用户在8月份练习的总题目数和回答正确的题目数情况,请取出相应明细数据,对于在8月份没有练习过的用户,答题数结果返回0

  • 复旦大学:university = '复旦大学',根据学校进行过滤
  • 每个用户:group by device_id,根据用户进行分组
  • 8月份:month(date) = '08',使用月份函数匹配月份
  • 总题目数:使用 count(question_id) 函数进行统计
  • 没有答题的用户,默认值为0

细节注意

  1. 没有练习过的用户,即在 question_practice_detail 表中无数据,而在 user_profile 表中有数据,因此以 user_profile 为主表,对应使用 left join 或者 right join
  2. 对答题的结果进行判断,如果为 right,则结果为1,否则,为0,进行求和计算

完整SQL

SELECT 
	t1.device_id,
	university,count(t2.question_id) as question_cnt,
	sum(if(t2.result = 'right',1,0)) as right_question_cnt
FROM
	user_profile t1
	left join question_practice_detail t2 on t1.device_id = t2.device_id and month(t2.date) = '08'
WHERE
	t1.university = '复旦大学' 
GROUP BY t1.device_id