包括当月:
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