明确题意:

统计出总作答次数total_pv、试卷已完成作答数complete_pv、已完成的试卷数complete_exam_cnt


问题分解:

  • 总作答次数:count(exam_id) as total_pv;
  • 试卷已完成作答数,count(A)会忽略A的值为null的行:count(submit_time) as complete_pv;
  • 已完成的试卷数,已完成时才计数用if判断,试卷可能被完成多次,需要去重用distinct:count(distinct if(submit_time is not null, exam_id, null)) as complete_exam_cnt

完整代码:

select
    count(exam_id) as total_pv,
    count(submit_time) as complete_pv,
    count(distinct if(submit_time is not null, exam_id, null)) as complete_exam_cnt
from exam_record