题解 | 统计复旦用户8月练题情况
select u.device_id, university, ifnull (count(question_id), 0) as question_cnt, ifnull ( sum( case when result = 'right' then 1 else 0 end ), 0 ) as right_question_cnt from user_profile u left join question_practice_detail qpd on qpd.device_id = u.device_id and month (date) = 8 where university = '复旦大学' group by u.device_id
先使用 LEFT JOIN
将 user_profile
表和 question_practice_detail
表连接起来,以确保即使某个用户在 8 月份没有练习记录,也会出现在结果集中(一开始将两个表连接反了,导致结果只有练习过的题目的)
筛选范围:日期为8月,university为复旦大学
聚合计算,按用户device_id分组
处理空值:使用 IFNULL()
(MySQL)函数处理可能出现的 NULL
值,将其转换为 0。