mysql 输出所在月份的最后一天

内置函数

sql 复制代码
LAST_DAY(date)

参数:

**date :**一个日期或日期时间类型的值,表示要获取所在月份最后一天的日期。

返回值:

返回一个日期值,表示输入日期所在月份的最后一天。

栗子

月总刷题数和日均刷题数_牛客题霸_牛客网 (nowcoder.com)

请从中统计出2021年每个月里用户的月总刷题数month_q_cnt 和日均刷题数avg_day_q_cnt(按月份升序排序)以及该年的总体情况,示例数据输出如下:

|--------------|-------------|---------------|
| submit_month | month_q_cnt | avg_day_q_cnt |
| 202108 | 2 | 0.065 |
| 202109 | 3 | 0.100 |
| 2021汇总 | 5 | 0.161 |

解释:2021年8月共有2次刷题记录,日均刷题数为2/31=0.065(保留3位小数);2021年9月共有3次刷题记录,日均刷题数为3/30=0.100;2021年共有5次刷题记录(年度汇总平均无实际意义,这里我们按照31天来算5/31=0.161)

建表语句:

sql 复制代码
drop table if exists practice_record;
CREATE TABLE  practice_record (
    id int PRIMARY KEY AUTO_INCREMENT COMMENT '自增ID',
    uid int NOT NULL COMMENT '用户ID',
    question_id int NOT NULL COMMENT '题目ID',
    submit_time datetime COMMENT '提交时间',
    score tinyint COMMENT '得分'
)CHARACTER SET utf8 COLLATE utf8_general_ci;

INSERT INTO practice_record(uid,question_id,submit_time,score) VALUES
(1001, 8001, '2021-08-02 11:41:01', 60),
(1002, 8001, '2021-09-02 19:30:01', 50),
(1002, 8001, '2021-09-02 19:20:01', 70),
(1002, 8002, '2021-09-02 19:38:01', 70),
(1003, 8002, '2021-08-01 19:38:01', 80);

题解:

sql 复制代码
select  DATE_FORMAT(submit_time,'%Y%m') as 'submit_month',
        count(*) as 'month_q_cnt',
		round(count(*)/MAX(DAY(last_day(submit_time))),3)
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 
from practice_record
where score is not null  and year(submit_time)=2021    
 group by DATE_FORMAT(submit_time,"%Y")
order by submit_month ; 
相关推荐
DFT计算杂谈23 分钟前
vasp如何计算金属的铁电极化强度?
数据库
EterNity_TiMe_32 分钟前
别让告警变成噪音:用Prometheus和Alertmanager搭一套可远程查看的监控系统
数据库·人工智能·ai·postgresql·prometheus·cpolar
不超限1 小时前
Postgresql 数据库 自增字段,Vastbase 无效的问题
数据库
阿坤带你走近大数据1 小时前
Oracle新老SQL写法对比
数据库·sql·oracle
还是鼠鼠1 小时前
AI掘金头条新闻系统 (Toutiao News)-缓存相关推荐新闻
后端·python·mysql·fastapi·web
努力努力再努力wz2 小时前
【高性能网络库与HTTP Server系列】:基于主从 Reactor 模型实现高性能 C++ 网络库与 HTTP Server
开发语言·网络·数据结构·数据库·c++·网络协议·http
HackTwoHub2 小时前
某单位 CMS 完整渗透链、SQL 注入→后台拿权→绕过宝塔 Waf 上线 shell
数据库·人工智能·sql·安全·网络安全·系统安全·安全架构
宠友信息2 小时前
Redis 内容社区源码架构优化与即时通讯数据一致性处理
spring boot·后端·websocket·mysql·uni-app
Elastic 中国社区官方博客3 小时前
使用 Elasticsearch 作为 Grafana 的直接替代 Prometheus 后端
大数据·数据库·sql·elasticsearch·搜索引擎·grafana·prometheus
杨婷1233 小时前
2026 企业微信会话存档服务商选型指南:一维助手方案深度解析
大数据·数据库·企业微信