SQL34 每份试卷每月作答数和截止当月的作答总数

题目主要信息:

  • 输出每份试卷每月作答数和截止当月的作答总数

问题拆分:

  • 求每份试卷每个月的作答数,要以exam_id,开始作答时间的月份进行分组。group by exam_id, month(start_time) 知识点:group by
  • 直接获取试卷ID、作答月份。
  • 对每组开始作答时间计数得到每份试卷每个月的作答数。知识点:count()
  • 以试卷分组,月份递增获取每份试卷每个月的累计和。sum(count(start_time)) over(partition by exam_id order by month(start_time)) as cum_exam_cnt 知识点:sum()over()、count()、partition by、order by

代码:

select exam_id, 
       date_format(start_time, '%Y%m') as start_month,
       count(start_time) as month_cnt,
       sum(count(start_time)) over(partition by exam_id order by month(start_time)) as cum_exam_cnt
from exam_record
group by exam_id, month(start_time)