'Cumulative Customer Revenue Across Cohort Chart - postgres

please help with the following query. I am trying to create a cohort chart that looks like this:

Register_month transacting_users 1_month 2_month 3_month
2022-01 58 $10
2021-12 21 $20 $39
2021-11 33 $21 $43 $65

month_3_spend is the cumultive average spend per customer. So for example, the average spend after being a customer for 3 months is $65 for customers who registered in November 2021.

How can I look at the cumulative average spend per user?

select
    c.customerid,
    to_char(c.timestampregistered,'YYYY-MM') as register_month,
    date_diff('months', trunc(c.timestampregistered), trunc(t.timestamp)) months_since_signup
from customers c
left join transactions t on c.memberid = t.memberid
group by 1,2,3
having months_since_signup is not null
order by 1,2
),

user_spend as (
select
    customerid,
    to_chartimestamp,'YYYY-MM') spend_month,
    sum(cost) revenue
from transactions
where t."timestamp" >= add_months(CURRENT_DATE,-3)
group by 2,1
order by 2 desc
)

select register_month, 
count(distinct(u.customerid)) transacting_users,
avg(case when months_since_signup = 1 then u.revenue else null end)::real 1_month,
avg(case when months_since_signup = 2 then u.revenue else null end)::real 2_month,
avg(case when months_since_signup = 3 then u.revenue else null end)::real 3_month
from cte
join user_spend u on cte.memberid = u.memberid
where signup_month >= add_months(CURRENT_DATE,-3)
group by signup_month
order by signup_month asc


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source