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;
如果你觉得不错,(点我)请我喝杯奶茶吧,O(∩_∩)O~
邮箱:wl131710@gmail.com、543253585@qq.com
★我的故乡江油市简介: 江油市是唐代大诗人李白的故乡,一座风景如画的历史文化名城,也是位于成都经济圈北端的一座正在崛起的新兴工业城市、旅游城市,素有“李白故里,九寨门户,蜀道咽喉,华夏诗城”之称。中国改革开放的总设计师邓小平为江油亲笔题写了“李白故里”四个苍劲有力的大字,近年来,又因著名武术大师海灯法师的影响而成为川北的武术之乡,可谓文武之光,交相辉映。此外,江油城郊的佛爷洞、金光洞均为川北名胜,作为古蜀道的重要通道,沿线古迹甚多。 李白纪念馆位于李白故里的昌明河畔,是一座具有唐代风格的古典园林建筑群,气韵飞动,豪放不羁,馆藏4000多件有关文物。