题解 | #每份试卷每月作答数和截止当月的作答总数。#
每份试卷每月作答数和截止当月的作答总数。
https://www.nowcoder.com/practice/5f1cbe74c682485aa73e4c2b30f04a62
# 先算出每个试卷的每月的做答数 # 再使用窗口函数进行累加 WITH temp_0 AS( SELECT exam_id, start_month, COUNT(start_month) month_cnt FROM ( SELECT exam_id, DATE_FORMAT(start_time, "%Y%m") start_month FROM exam_record ) b GROUP BY exam_id, start_month ) SELECT exam_id, start_month, month_cnt, SUM(month_cnt) OVER(PARTITION BY exam_id ORDER BY start_month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cum_exam_cnt FROM temp_0
犯的错: PARTITION 写错为PATITION
只有一个表,先求每个试卷的每月做题数,要使用DATE_FORMAT,还有分组
最后主查询使用SUM()即可,不使用窗口帧时,就是默认从该分组的第一行开始计算,直到当前行,同我的窗口帧的定义。
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
:与默认行为相同,从分组的开始到当前行。ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
:仅包含当前行和其前一行。ROWS BETWEEN 3 PRECEDING AND 1 FOLLOWING
:包含当前行、其前三行和后一行。