Mysql 查询统计最近12个月的数据

包括当月:

sql 复制代码
SELECT
	t1.yf AS 'month',
	count( t2.uuid ) AS total
FROM
	(
	SELECT
		DATE_FORMAT(( CURDATE()), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 1 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 2 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 3 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 4 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 5 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 6 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 7 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 8 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 9 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 10 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 11 MONTH ), '%Y-%m' ) AS 'yf'
	) t1
	LEFT JOIN 表名 t2 ON DATE_FORMAT( t2.时间日期字段, '%Y-%m' )= t1.yf
GROUP BY
yf

不包括当月:

sql 复制代码
SELECT
	t1.yf AS 'month',
	count( t2.uuid ) AS total
FROM
	(
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 1 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 2 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 3 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 4 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 5 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 6 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 7 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 8 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 9 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 10 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 11 MONTH ), '%Y-%m' ) AS 'yf' UNION
	SELECT
		DATE_FORMAT(( CURDATE() - INTERVAL 12 MONTH ), '%Y-%m' ) AS 'yf'
	) t1
	LEFT JOIN 表名 t2 ON DATE_FORMAT( t2.日期字段, '%Y-%m' )= t1.yf
GROUP BY
yf
相关推荐
远歌已逝3 小时前
维护在线重做日志(二)
数据库·oracle
qq_433099404 小时前
Ubuntu20.04从零安装IsaacSim/IsaacLab
数据库
Dlwyz4 小时前
redis-击穿、穿透、雪崩
数据库·redis·缓存
工业甲酰苯胺6 小时前
Redis性能优化的18招
数据库·redis·性能优化
没书读了7 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
i道i7 小时前
MySQL win安装 和 pymysql使用示例
数据库·mysql
小怪兽ysl7 小时前
【PostgreSQL使用pg_filedump工具解析数据文件以恢复数据】
数据库·postgresql
武子康7 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
wqq_9922502778 小时前
springboot基于微信小程序的食堂预约点餐系统
数据库·微信小程序·小程序
爱上口袋的天空8 小时前
09 - Clickhouse的SQL操作
数据库·sql·clickhouse