题解 | 统计复旦用户8月练题情况
select a.device_id,university, sum( case when question_id is not null then 1 else 0 end ) as question_cnt , sum( case when result = 'right' then 1 else 0 end ) as right_question_cnt from user_profile a left join question_practice_detail b on a.device_id = b.device_id and month(b.date) = 8 where a.university = '复旦大学' group by device_id
坑点主要是如果过滤8月数据。首先要保留没有匹配到8月数据的同学,所以采用左连接没啥好说的;其次,过滤8月数据的时候,不要放在where里面过滤整个连接后的结果集,这样会导致左连接失去意义,过滤的作用是不作用于a表只作用于b表,所以放在on上面过滤b表。
另一个小技巧是,count统计只能死板的作用于分组字段,但是sum聚合函数则可以在内部使用case when 做进一步过滤,分组之后可以做更加细致的过滤