ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Mysql 时间格式化 date_format

2026/8/18 6:03:26 拓冰建站 浏览量
Mysql 时间格式化 date_format

有没有遇到过类似这样的问题,将日期 ‘2023-02-23‘ 的格式转化为 202302的格式。

可能有些小伙伴,会直接想到字符串拼接 concat(year(2023-02-23),month(2023-02-23))得到的也是 202302。那要是要求必须是时间格式呢,可能有些小伙伴会说再将其转为时间格式,这样就太麻烦了。

日期格式化

DATE_FORMAT(date,format)

date 参数是合法的日期。format 规定日期/时间的输出格式。

常见的使用的格式有:

描述
%Y年,4 位
%y年,2 位
%M月名
%b缩写月名
%m月,数值(00-12)  
%c月,数值
%W星期名
%a缩写星期名
%d月的天,数值(00-31)
%e月的天,数值(0-31)
%j年的天 (001-366)
%w周的天 (0=星期日, 6=星期六)
%H小时 (00-23)
%h小时 (01-12)
%i分钟,数值(00-59)
%S秒(00-59)
%s秒(00-59)
%f微秒
%pAM 或 PM
%r时间,12-小时(hh:mm:ss AM 或 PM)
%T时间, 24-小时 (hh:mm:ss)

栗子

平均活跃天数和月活人数_牛客题霸_牛客网 (nowcoder.com)

请计算2021年每个月里试卷作答区用户平均月活跃天数avg_active_days和月度活跃人数mau,

上面数据的示例输出如下:

monthavg_active_daysmau
2021071.502
2021091.254

解释:2021年7月有2人活跃,共活跃了3天(1001活跃1天,1002活跃2天),平均活跃天数1.5;2021年9月有4人活跃,共活跃了5天,平均活跃天数1.25,结果保留2位小数。

注:此处活跃指有交卷行为。

建表语句:

drop table if exists exam_record;
CREATE TABLE exam_record (id int PRIMARY KEY AUTO_INCREMENT COMMENT '自增ID',uid int NOT NULL COMMENT '用户ID',exam_id int NOT NULL COMMENT '试卷ID',start_time datetime NOT NULL COMMENT '开始时间',submit_time datetime COMMENT '提交时间',score tinyint COMMENT '得分'
)CHARACTER SET utf8 COLLATE utf8_general_ci;INSERT INTO exam_record(uid,exam_id,start_time,submit_time,score) VALUES
(1001, 9001, '2021-07-02 09:01:01', '2021-07-02 09:21:01', 80),
(1002, 9001, '2021-09-05 19:01:01', '2021-09-05 19:40:01', 81),
(1002, 9002, '2021-09-02 12:01:01', null, null),
(1002, 9003, '2021-09-01 12:01:01', null, null),
(1002, 9001, '2021-07-02 19:01:01', '2021-07-02 19:30:01', 82),
(1002, 9002, '2021-07-05 18:01:01', '2021-07-05 18:59:02', 90),
(1003, 9002, '2021-07-06 12:01:01', null, null),
(1003, 9003, '2021-09-07 10:01:01', '2021-09-07 10:31:01', 86),
(1004, 9003, '2021-09-06 12:01:01', null, null),
(1002, 9003, '2021-09-01 12:01:01', '2021-09-01 12:31:01', 81),
(1005, 9001, '2021-09-01 12:01:01', '2021-09-01 12:31:01', 88),
(1006, 9002, '2021-09-02 12:11:01', '2021-09-02 12:31:01', 89),
(1007, 9002, '2020-09-02 12:11:01', '2020-09-02 12:31:01', 89);

题解:

select date_format(submit_time,'%Y%m') as month,round((count( distinct uid,date_format(submit_time, '%y%m%d'))) / count(distinct uid),2) as avg_active_days,count(distinct uid) as mau
from exam_record
where submit_time is not null and year(submit_time)=2021
group by date_format(submit_time, '%Y%m')