Postgres SQL for循环统计每月现有用户



我有一个用户数据库,用于记录用户注册时间:

id,  signup_time
100    2020-09-01
001    2018-01-01
....

如何找到所有历史记录的每月现有用户?使用当月的最后一天作为截止日,现有用户意味着,如果我在2020-07-31年7月的最后一日观察到,该用户在2020-07-01年之前已经注册。如果我在6月的最后一天2020-06-30观察到,这个用户在2020-06-01之前就已经注册了。

类似于其他语言中的for循环:

observation_year_month_list = ['2020-04','2020-05','2020-06']
for i in observation_year_month_list:

if user signup_time  < i:
monthly_existing_user_count+1

虽然PL/SQL有循环,但它是过程语言的扩展。SQL是一种声明性语言,不使用循环。相反,您描述您想要的结果,然后数据库会提出一个查询计划来实现它。

您的案例由group by处理,以便将行聚合到组中。在这种情况下,使用date_trunc按月计算。然后使用聚合函数count来计算每组中有多少用户。

select
count(id) as num_users,
date_trunc('month', signup_time) as signup_month
from users
group by date_trunc('month', signup_time)

最新更新