码迷,mamicode.com
首页 > 数据库 > 详细

sql按月统计数量和按月累加统计数量

时间:2018-04-26 19:08:45      阅读:353      评论:0      收藏:0      [点我收藏+]

标签:format   form   and   group   mat   _for   sof   strong   create   

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按月统计数量和按月累加统计数量

标签:format   form   and   group   mat   _for   sof   strong   create   

原文地址:https://www.cnblogs.com/wanglu/p/8954409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!