根据题目可知几个限定条件
1.学校为复旦大学,即 user_profile.university='复旦大学';
2.练习月份为8月,即 month(question_practice_detail.date)='08';
3.8月未练习的用户,练习题目数和正确数都为0,用 if 和 case when 都可,看个人习惯
主要考察 join 和 if、case when 用法
捋清楚限定条件后,开始写代码,比较习惯用 with as,所以这里也用了 with as
-- 1.复旦大学用户 with user_fd as (select id, device_id, university from user_profile where university='复旦大学' ), -- 2.8月用户练习记录 que as ( select device_id, count(question_id) as question_cnt sum(case when result='right' then 1 else 0 end) as right_question_cnt from question_practice_detail where month(date)='08' group by device_id ) --3.left join 后,对于8月未练习的复旦用户,答题数和正确数均赋值为0,得出结果 select user_fd.device_id, user_fd.university, case when que.question_cnt is null then 0 else que.question_cnt end as question_cnt, case when que.right_question_cnt is null then 0 else que.right_question_cnt end as right_question_cnt from user_fd left join que on user_fd.device_id=que.device_id