明确题意:
统计出2021年每个月里用户的月总刷题数month_q_cnt 和日均刷题数avg_day_q_cnt,以及该年的总体情况
问题拆解:
- 本题主要是考察知识点:group by、date_format、day、last_day、round、union all
- DATE_FORMAT(submit_time, "%Y%m" ) 返回的是202109这样;day('2021-08-02 11:41:01')返回的是2,last_day('2021-08-02 11:41:01')返回的是2021-08-31,last_day('2021-09-02 11:41:01')返回的是2021-09-30
- 先按月份分组
- month_q_cnt = 当月的记录总数
-
avg_day_q_cnt = month_q_cnt / 当月的天数,通过day(last_day(...))得到当月的天数
- union all 汇总的数据。多个表union all时不会去重记录,字段名、字段顺序、字段类型要一致。
代码实现:
select DATE_FORMAT(submit_time,'%Y%m') as submit_month, count(*) as month_q_cnt, round(count(*) / day(last_day(submit_time)) ,3) as avg_day_q_cnt from practice_record where score is not null and year(submit_time) = '2021' group by DATE_FORMAT(submit_time,'%Y%m') union all select '2021汇总' as submit_month, count(*) as month_q_cnt, round(count(*) /31 ,3) as avg_day_q_cnt -- /30 会不通过用例 from practice_record where score is not null and year(submit_time) = '2021' order by submit_month ;
不足之处,欢迎指正