题解 | #月总刷题数和日均刷题数#
月总刷题数和日均刷题数
http://www.nowcoder.com/practice/f6b4770f453d4163acc419e3d19e6746
- 运行正确
select coalesce(year_mon,'2021汇总') as submit_month,
count(question_id) as month_q_cnt,
round(count(question_id)/max(t.days_month),3) as avg_day_cnt
from
(select question_id,
dayofmonth(last_day(submit_time)) as days_month,
date_format(submit_time,'%Y%m') as year_mon
from practice_record
where year(submit_time)=2021) as t
group by t.year_mon
with rollup;
解析
题目:月总刷题数month_q_cnt 和日均刷题数avg_day_q_cnt(按月份升序排序),该年的总体情况
约束条件:2021年每月,date_format(submit_time,'%y%m')=2021xx
-
月总刷题数(month_q_cnt)=count(question_id) group by 月份
-
日均刷题数avg_day_q_cnt=月总刷题记录/月天数,(按月份升序排序)order by date_format(submit_time,'%y%m') 保留三位小数,round(,3)
-
月天数:dayofmonth(last_day())返回每月天数
-
DAYOFMONTH(d) 函数返回 d 是一个月中的第几天,范围为 1~31。例如 DAYOFMONTH('2017-12-15') 2017-12-15 是这个月的第 15 天。
-
LAST_DAY()函数是取某个月最后一天的日期。
-
MAX 函数返回一列中的最大值。NULL 值不包括在计算中。
- 该年的总体情况
新知识
MySQL提供了 group by with rollup 函数进行group by 字段的汇总,但是与order by 互斥,不能同时用
COALESCE是一个函数, (expression_1, expression_2, ...,expression_n) 作用:用途: (1):将控制替换成其他值;
(2):返回第一个非空值
解释一下为什么本题用max()
- 第一个代码中的t表
question_id | days_month | year_mon |
---|---|---|
8001 | 31 | 202108 |
8002 | 31 | 202108 |
8001 | 30 | 202109 |
8002 | 30 | 202109 |
- sql的执行顺序:from,where,group by,having,select,order by 那么本题 select 字段 from t group by 字段 如果不用max,会报错,因为同一个月份,question_id有两个不同的值,如果上表看着迷糊,看下表
question_id | days_month | year_mon |
---|---|---|
8001 | 31 | 202108 |
8001 | 30 | 202109 |
8002 | 31 | 202108 |
8002 | 30 | 202109 |
- 加order by 错误
select coalesce(year_mon,'2021汇总') as submit_month,
count(question_id) as month_q_cnt,
round(count(question_id)/max(t.days_month),3) as avg_day_cnt
from
(select question_id,
dayofmonth(last_day(submit_time)) as days_month,
date_format(submit_time,'%Y%m') as year_mon
from practice_record
where year(submit_time)=2021) as t
group by t.year_mon
with rollup
order by t.year_mon;