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;

 

posted @ 2018-04-26 18:46  三月路  阅读(38283)  评论(1编辑  收藏  举报