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

Postgresql count rows per date adding up

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

因此我写了一个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 语句或不同的方法来实现此目的?我希望你能帮助我。

您可以使用 window 函数来做到这一点:

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是保留关键字,需要加引号,否则不能作为标识符使用。

试试这个:

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;