题解 | #月总刷题数和日均刷题数#

月总刷题数和日均刷题数

http://www.nowcoder.com/practice/f6b4770f453d4163acc419e3d19e6746

明确题意:

统计出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 ;



不足之处,欢迎指正

全部评论
ound(count(*) / day(last_day(submit_time)) ,3) as avg_day_q_cnt 这句话执行不出来把,这个day(last_day(submit_time))这个没有进行分组,也就是这个多条数据,你需要讲这个取均值,这样则为一条数据
5 回复 分享
发布于 2021-12-23 21:03
您好,请问为什么最后一行order by submit_month没有时会报错呢~
2 回复 分享
发布于 2021-12-06 23:43
请问为什么要where score is not null?
1 回复 分享
发布于 2022-08-01 13:49
直接复制的,运行不出来
1 回复 分享
发布于 2021-12-15 14:01
应该是avg(day(last_day(submit_time))
4 回复 分享
发布于 2022-01-27 17:16
round(count(uid)/ day(last_day(submit_time)),3) as avg_day_q_cnt 改为 round(count(uid)/ max(day(last_day(submit_time))),3) as avg_day_q_cnt就可以了
3 回复 分享
发布于 2022-06-08 07:55
复制代码都运行不出来结果,难过
3 回复 分享
发布于 2021-12-08 16:32
运行错误,现在已经跑不起来了
1 回复 分享
发布于 2022-05-25 10:26
太强了哥
点赞 回复 分享
发布于 10-19 19:44 江苏
用uid做索引更好!count(uid)
点赞 回复 分享
发布于 2022-04-04 15:20
day(last_day(submit_time))换成avg(day(last_day(submit_time)))
点赞 回复 分享
发布于 2022-04-04 15:19
last_day(submit_time)已经是30或者31了,为什么还要加day(),出来结果不还是30或者31吗?
点赞 回复 分享
发布于 2022-03-23 14:46
复制代码还一直报错
点赞 回复 分享
发布于 2022-03-03 16:28
汇总的日均练题数为啥是除以31呢
点赞 回复 分享
发布于 2022-02-21 14:08
请问group by 后面为什么不能直接用submit_month呢?需要用date_format
点赞 回复 分享
发布于 2022-02-10 21:04
count(*)浪费时间了,换成count(uid)
点赞 回复 分享
发布于 2022-02-07 09:39
请问为什么2021汇总那一段不需要再写group by了呢
点赞 回复 分享
发布于 2021-12-23 13:30
SQL_ERROR_INFO: "Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'practice_record.submit_time' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by"
点赞 回复 分享
发布于 2021-12-15 14:02

相关推荐

包行:平时怎么刷算法题的哇,字节的手撕听说都很难
字节跳动工作体验
点赞 评论 收藏
分享
评论
49
8
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务