查询以确定从用户注册到第一次购买的平均持续时间

f45qwnt8  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(258)

我的postgresql数据库中有以下表:

users: id, created_at (timestamp)
purchases: id, created_at

一个用户可以有多个购买。我想了解的是,在特定月份创建的用户,他们第一次购买前的平均时间长度是多少。这应该只包括购买1次或更多的用户。
目标是让数据看起来像这样:

weeks_ago | Date Start | Date End | Total Users in Cohort | Total Users w >=1 Purchase | avg days to complete 1st purchase

我可以尝试什么方法?

dldeef67

dldeef671#

嗯。假设第一次购买总是在创建日期之后,那么您基本上需要执行以下操作:
汇总采购以获得第一个采购日期(或使用 distinct on ). JOIN 结果是 users table。
按月汇总。
这看起来像:

select date_trunc('month', u.created_at) as yyyymm,
       avg( u.created_at - p.created_at )
from users u join
     (select p.id, min(p.created_at) as first_created_at
      from purchases p
      group by p.id
     ) p
     on u.id = p.id
group by date_trunc('month', u.created_at)

相关问题