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

项目场景:

mysql查询统计最近12个月的数据,按每个月纵向展示,效果图

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


sql语句

注意:count( v.uuid ) 这里的是被统计那张表的id

SELECT m.`month`,count( v.uuid ) AS total
FROM (
    SELECT DATE_FORMAT(( CURDATE()), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 1 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 2 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 3 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 4 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 5 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 6 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 7 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 8 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 9 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 10 MONTH ), '%Y-%m' ) AS `month` UNION
    SELECT DATE_FORMAT(( CURDATE() - INTERVAL 11 MONTH ), '%Y-%m' ) AS `month`
) m
LEFT JOIN test v ON DATE_FORMAT( v.create_time, '%Y-%m' ) = m.`month`
GROUP BY m.`month` order by m.`month`

原文:

Mysql 查询统计最近12个月的数据_mysql查询最近12个月的数据-CSDN博客

你可能感兴趣的:(数据库,mysql,时间统计,月份统计,最近12个月,月份)