-- 存储过程代码
CREATE PROCEDURE `proc_statistics`()
BEGIN
-- 按小时分组
CREATE TEMPORARY TABLEIFNOT EXISTS `tmp_statistics_hour` (
`stat_time` DATETIME NOTNULL,
`count` INT UNSIGNED NOTNULL DEFAULT 0,
PRIMARYKEY (`stat_time`)
);
INSERTINTO `tmp_statistics_hour` (`stat_time`, `count`)
SELECT DATE_FORMAT(`created_at`, '%Y-%m-%d %H:00:00') AS `stat_time`, COUNT(*) AS `count`
FROM `table_name`
WHERE `created_at` BETWEEN DATE_SUB(NOW(), INTERVAL 1 DAY) AND NOW()
GROUP BY `stat_time`;
-- 按天分组
CREATE TEMPORARY TABLEIFNOT EXISTS `tmp_statistics_day` (
`stat_time` DATE NOTNULL,
`count` INT UNSIGNED NOTNULL DEFAULT 0,
PRIMARYKEY (`stat_time`)
);
INSERTINTO `tmp_statistics_day` (`stat_time`, `count`)
SELECT DATE(`created_at`) AS `stat_time`, COUNT(*) AS `count`
FROM `table_name`
WHERE `created_at` BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
GROUP BY `stat_time`;
-- 按月分组
CREATE TEMPORARY TABLEIFNOT EXISTS `tmp_statistics_month` (
`stat_time` DATE NOTNULL,
`count` INT UNSIGNED NOTNULL DEFAULT 0,
PRIMARYKEY (`stat_time`)
);
INSERTINTO `tmp_statistics_month` (`stat_time`, `count`)
SELECT DATE_FORMAT(`created_at`, '%Y-%m-01') AS `stat_time`, COUNT(*) AS `count`
FROM `table_name`
WHERE `created_at` BETWEEN DATE_SUB(NOW(), INTERVAL 1 YEAR) AND NOW()
GROUP BY `stat_time`;
-- 补0
SELECT `stat_time`, IFNULL(`count`, 0) AS `count`
FROM (
SELECT `stat_time` FROM `tmp_statistics_hour`
UNION SELECT `stat_time` FROM `tmp_statistics_day`
UNION SELECT `stat_time` FROM `tmp_statistics_month`
) AS `tmp_stat_time`
LEFT JOIN `tmp_statistics_hour` ON `tmp_stat_time`.`stat_time` = `tmp_statistics_hour`.`stat_time`
LEFT JOIN `tmp_statistics_day` ON `tmp_stat_time`.`stat_time` = `tmp_statistics_day`.`stat_time`
LEFT JOIN `tmp_statistics_month` ON `tmp_stat_time`.`stat_time` = `tmp_statistics_month`.`stat_time`
ORDERBY `stat_time` ASC;
-- 删除临时表
DROP TEMPORARY TABLEIF EXISTS `tmp_statistics_hour`;
DROP TEMPORARY TABLEIF EXISTS `tmp_statistics_day`;
DROP TEMPORARY TABLEIF EXISTS `tmp_statistics_month`;
END;
暂无评论