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
相关推荐
师太,答应老衲吧2 小时前
SQL实战训练之,力扣:2020. 无流量的帐户数(递归)
数据库·sql·leetcode
Yaml43 小时前
Spring Boot 与 Vue 共筑二手书籍交易卓越平台
java·spring boot·后端·mysql·spring·vue·二手书籍
Channing Lewis3 小时前
salesforce case可以新建一个roll up 字段,统计出这个case下的email数量吗
数据库·salesforce
追风林3 小时前
mac 本地docker-mysql主从复制部署
mysql·macos·docker
毕业设计制作和分享4 小时前
ssm《数据库系统原理》课程平台的设计与实现+vue
前端·数据库·vue.js·oracle·mybatis
ketil274 小时前
Redis - String 字符串
数据库·redis·缓存
NiNg_1_2344 小时前
高级 SQL 技巧详解
sql
Hsu_kk5 小时前
MySQL 批量删除海量数据的几种方法
数据库·mysql
编程学无止境5 小时前
第02章 MySQL环境搭建
数据库·mysql
knight-n5 小时前
MYSQL库的操作
数据库·mysql