MYSQL 日月周季年分组
首先准备几条测试数据
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`n_id` int(11) DEFAULT NULL,
`d_createdate` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of test
-- ----------------------------
INSERT INTO `test` VALUES ('1', '2020-05-12 14:00:36');
INSERT INTO `test` VALUES ('2', '2020-04-12 14:00:47');
INSERT INTO `test` VALUES ('3', '2019-11-12 14:00:51');
- 通过日分组,此时不需要函数处理,直接group by 日期字段即可
SELECT
d_createdate,
DATE_FORMAT(d_createdate, '%Y%m%d') days
FROM
test
GROUP BY
days; - 通过周分组,使用DATE_FORMAT指定格式即可
SELECT
d_createdate,
DATE_FORMAT(d_createdate, '%Y%u') weeks
FROM
test
GROUP BY
weeks; - 通过月分组,同理使用DATE_FORMAT指定格式即可
SELECT
d_createdate,
DATE_FORMAT(d_createdate, '%Y%m') months
FROM
test
GROUP BY
months; - 通过季度分组,使用QUARTER
SELECT
d_createdate,
QUARTER (d_createdate) qu
FROM
test
GROUP BY
qu; - 通过年分组,使用YEAR函数
SELECT
d_createdate,
YEAR (d_createdate) y
FROM
test
GROUP BY
y;