在某些业务场景中,需要后台获取连续十二个月的统计数据,如下图:
该表的最大数量决定统计返回的最大条数
CREATE TABLE `sys_redundancy` (
`id` bigint(22) NOT NULL AUTO_INCREMENT COMMENT '序号',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8 COMMENT='冗余必须表:目前用于用户注册统计,该表的数量决定用户统计返回的条数';
插入连续1000条数据
DROP PROCEDURE IF EXISTS proc_initData;
DELIMITER $
CREATE PROCEDURE proc_initData()
BEGIN
DECLARE i INT DEFAULT 1;
WHILE i<=1000 DO
INSERT INTO sys_redundancy(id) VALUES(i);
SET i = i+1;
END WHILE;
END $
DELIMITER ;
CALL proc_initData();
select * from(
SELECT
IFNULL(count(a.user_id), 0) AS sum,
b.tdate AS date
FROM
sys_user a
RIGHT JOIN (
SELECT
DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL n.id-1 MONTH),'%Y-%m') AS tdate
FROM
sys_redundancy n
) b ON DATE_FORMAT(a.create_time,'%Y-%m') = b.tdate and a.user_type = 2
GROUP BY
b.tdate
ORDER BY b.tdate desc
limit 12) m
ORDER BY m.date asc
;