Mysql 最近三个月的数据统计

mysql 统计某张表中最近三个月的数据

SELECT
t.year_month as yearMonth,
count(表名.字段名) as count
FROM
(SELECT
DATE_FORMAT(CURDATE(), ‘%Y-%m’) AS year_month
UNION SELECT
DATE_FORMAT((CURDATE() - INTERVAL 1 MONTH), ‘%Y-%m’) AS year_month
UNION SELECT
DATE_FORMAT((CURDATE() - INTERVAL 2 MONTH), ‘%Y-%m’) AS year_month
) t
LEFT JOIN
表名
on DATE_FORMAT(表名.日期字段名,’%Y-%m’) = t.year_month
GROUP BY t.year_month
ORDER BY t.year_month desc

例如: 统计 user 表中最近三个月的数据

 SELECT
           t.year_month as yearMonth,
           count(u.create_time) as count
       FROM
   	    (SELECT
   	        DATE_FORMAT(CURDATE(), '%Y-%m') AS `year_month`
           UNION SELECT
               DATE_FORMAT((CURDATE() - INTERVAL 1 MONTH), '%Y-%m') AS `year_month`
           UNION SELECT
               DATE_FORMAT((CURDATE() - INTERVAL 2 MONTH), '%Y-%m') AS `year_month`
           ) t
       LEFT JOIN
           user u
       on DATE_FORMAT(u.create_time,'%Y-%m') = t.year_month
       GROUP BY t.`year_month`
       ORDER BY t.`year_month` desc

结果
Mysql 最近三个月的数据统计_第1张图片

你可能感兴趣的:(Mysql 最近三个月的数据统计)