Postgresql计算每个日期的行数加起来

时间:2016-09-13 09:25:28

标签: sql postgresql count cumulative-sum

我试图制作一个可以跟踪不断增加的用户数量的图表。

因此,我编写了一个SQL语句,搜索特定时期内新添加的用户:

select distinct Createtime, count (user_id) as new_users 
from user 
where createtime between '2015-12-03 00:00:00' and CURRENT_DATE 
group by createtime 
order by createtime asc;

显示以下结果:

createtime|new_users
---------------------
2015-12-04|    1
2016-01-20|    1     
2016-02-03|    5
2016-02-04|    1

我想将结果加起来以获得每个日期的当前用户数,因此结果看起来应该更像:

createtime|new_users
---------------------
2015-12-04|    1
2016-01-20|    2     
2016-02-03|    7
2016-02-04|    8

是否有SQL语句或其他方法来实现此目的?我希望你能帮助我。

2 个答案:

答案 0 :(得分:1)

您可以使用窗口功能执行此操作:

select createtime, sum(new_users) over (order by createtime) as new_users
from (
  select createtime::date as createtime, count(user_id) as new_users 
  from "user"
  where createtime between '2015-12-03 00:00:00' and CURRENT_DATE 
  group by createtime 
) t
order by createtime asc;

user是保留关键字,需要引用,否则您不能将其用作标识符。

答案 1 :(得分:0)

试试这个:

select x.Createtime, 
(select count (sub.user_id) from USER sub 
WHERE sub.createtime between '2015-12-03 00:00:00' and x.Createtime )as new_users 
from user x
where createtime between '2015-12-03 00:00:00' and CURRENT_DATE 
group by createtime 
order by createtime asc;