sql按月统计数量和按月累加统计数量
Posted 开
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql按月统计数量和按月累加统计数量相关的知识,希望对你有一定的参考价值。
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;
以上是关于sql按月统计数量和按月累加统计数量的主要内容,如果未能解决你的问题,请参考以下文章