2017-05-26 62 views
0

分組有用戶與以前的數據

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 

回答

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這樣的人會告訴你。

+0

這不是一個窗口函數嗎? – Strawberry