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 ; 
相关推荐
马克Markorg4 小时前
常见的向量数据库和具有向量数据库能力的数据库
数据库
百锦再5 小时前
React编程高级主题:测试代码
android·前端·javascript·react.js·前端框架·reactjs
2501_916008896 小时前
全面介绍Fiddler、Wireshark、HttpWatch、SmartSniff和firebug抓包工具功能与使用
android·ios·小程序·https·uni-app·iphone·webview
Coder_Boy_7 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
玉梅小洋7 小时前
Windows 10 Android 构建配置指南
android·windows
helloworldandy7 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
Libraeking8 小时前
视觉篇:Canvas 自定义绘图与高级动画的华丽圆舞曲
android·经验分享·android jetpack
数据知道8 小时前
PostgreSQL 故障排查:如何找出数据库中最耗时的 SQL 语句
数据库·sql·postgresql
qq_12498707538 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
枷锁—sha9 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全