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

包括当月:

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

Mysql 查询统计最近12个月的数据_第1张图片

不包括当月:

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

 Mysql 查询统计最近12个月的数据_第2张图片

 

你可能感兴趣的:(mysql,数据库,sql)