1、简单的,按月统计数量
SELECT CREATE_DATE, DATE_FORMAT(CREATE_DATE, ‘%Y-%m‘) AS month , COUNT(*) AS sum FROM pt_user GROUP BY month;
2、按月累加统计数据
SELECT a.month, SUM(b.total) AS total FROM ( SELECT DATE_FORMAT(CREATE_DATE, ‘%Y-%m‘) AS month, SUM(sum) AS total FROM ( SELECT CREATE_DATE, DATE_FORMAT(CREATE_DATE, ‘%Y-%m‘) AS month , COUNT(*) AS sum FROM pt_user GROUP BY month ) ptuser GROUP BY month ) a JOIN ( SELECT DATE_FORMAT(CREATE_DATE, ‘%Y-%m‘) AS month, SUM(sum) AS total FROM ( SELECT CREATE_DATE, DATE_FORMAT(CREATE_DATE, ‘%Y-%m‘) AS month , COUNT(*) AS sum FROM pt_user GROUP BY month ) ptuser GROUP BY month ) b ON a.MONTH >= b.MONTH GROUP BY a.MONTH ORDER BY a.month;
3、多字段按月累加统计(eg:按租户统计累加每月增长数量)
SELECT a.ORGAN_ID, a.month, SUM(b.total) AS total FROM ( SELECT ORGAN_ID, DATE_FORMAT(CREATE_TIME, ‘%Y-%m‘) AS month , SUM(sum) AS total FROM ( SELECT ORGAN_ID, CREATE_TIME, DATE_FORMAT(CREATE_TIME, ‘%Y-%m‘) AS month , COUNT(*) AS sum FROM pt_user GROUP BY month ) ptuser GROUP BY ORGAN_ID, month ) a JOIN ( SELECT ORGAN_ID, DATE_FORMAT(CREATE_TIME, ‘%Y-%m‘) AS month , SUM(sum) AS total FROM ( SELECT ORGAN_ID, CREATE_TIME, DATE_FORMAT(CREATE_TIME, ‘%Y-%m‘) AS month , COUNT(*) AS sum FROM pt_user GROUP BY month ) ptuser GROUP BY ORGAN_ID, month ) b ON a.ORGAN_ID = b.ORGAN_ID AND a.MONTH >= b.MONTH GROUP BY a.MONTH ORDER BY a.ORGAN_ID, a.month;
原文地址:https://www.cnblogs.com/wanglu/p/8954409.html
时间: 2024-10-22 04:42:45