如何在结果列上对PostgreSQL进行累积求和?

时间:2015-10-02 14:30:09

标签: postgresql

我有这个PostgreSQL查询,可以获取已注册用户的总数:

SELECT concat(extract(MONTH from created_at),'-', extract(year from created_at)) AS "Month", 
count(case when is_accountant='t' then email end) AS "Total AB Signups",
count(case when is_accountant='f' then email end) AS "Total SMB Signups",
COALESCE(count(case when is_accountant='t' then email end))
+COALESCE(count(case when is_accountant='f' then email end)) as "Total Signups"
from users
group by 1,extract(month from created_at),extract(year from created_at)
HAVING count(case when is_accountant='t' then email end)<>0 
AND count(case when is_accountant='f' then email end)<>0
order by extract(year from created_at),extract(month from created_at); 

结果是这样的:

Month   | Total AB Signups | Total SMB Signups | Total Signups
-------------------------------------------------------------
08-2015 | 2                | 5                 | 7
09-2015 | 4                | 8                 | 12

如何为累积总和添加一列,如下所示?

Month   | Total AB Signups | Cumulative AB | Total SMB Signups | Cumulative SMB | Total Signups | Cumulative Total
-----------------------------------------------------------------------------------------------------------------
08-2015 | 2                | 2             |5                  | 5              | 7             | 7
09-2015 | 4                | 6             |8                  | 13             | 12            | 19

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
   CONCAT("Month", '-', "Year") AS "Month / Year",
   "Total AB Signups",
   SUM("Total AB Signups") OVER (ORDER BY "Year", "Month") AS "Cumulative AB",
   "Total SMB Signups",
   SUM("Total SMB Signups") OVER (ORDER BY "Year", "Month") AS "Cumulative SMB",
   "Total AB Signups" + "Total SMB Signups" AS "Total Signups",
   SUM("Total AB Signups" + "Total SMB Signups") 
   OVER (ORDER BY "Year", "Month") AS "Cumulative Total"       
FROM (
SELECT EXTRACT(YEAR FROM created_at) AS "Year",
       EXTRACT(MONTH FROM created_at) AS "Month",
       COUNT(CASE WHEN is_accountant='t' THEN email END) AS "Total AB Signups",
       COUNT(CASE WHEN is_accountant='f' THEN email END) AS "Total SMB Signups"
FROM users
GROUP BY 1, EXTRACT(MONTH FROM created_at), EXTRACT(YEAR FROM created_at)
HAVING COUNT(CASE WHEN is_accountant='t' THEN email END) <> 0 
       AND COUNT(CASE WHEN is_accountant='f' THEN email END) <> 0 ) AS t
ORDER BY "Year", "Month"

这个想法很简单:将SUMOVER (ORDER BY ...)一起应用于原始查询生成的派生表。