使用以前的数据进行分组

时间:2017-05-26 12:54:50

标签: sql oracle group-by running-total

有一个用户表

ID | DATE_CR

逐月分组

SELECT TO_CHAR (operation_time, 'YYYY-MM'), count(ID) from users GROUP BY TO_CHAR (operation_time, 'YYYY-MM')

我得到了注册的月数

January 10
February 3
March 5

但是在输出中,我想得到

January 10
February 13
March 18

1 个答案:

答案 0 :(得分:0)

一种方法是将当前查询放入CTE,然后使用相关子查询计算运行总计。

WITH cte AS (
    SELECT
        TO_CHAR (operation_time, 'YYYY-MM') AS mdate,
        COUNT(ID) AS total
    FROM users
    GROUP BY TO_CHAR (operation_time, 'YYYY-MM')
)
SELECT t1.mdate,
       (SELECT SUM(t2.total) FROM cte t2
        WHERE t2.mdate <= t1.mdate) AS running_total
FROM cte t1

另一种可能表现更好的方法是使用窗口函数。像@GordonLinoff这样的人会告诉你这件事。