Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

postgresql - Is there a SQL code for cumulative count of SaaS customer over months?

I have a table with: ID (id client), date_start (subscription of SaaS), date_end (could be a date value or be NULL).

So I need a cumulative count of active clients month by month.

any idea on how to write that in Postgres and achieve this result? enter image description here

Starting from this, but I don't know how to proceed

select 
date_trunc('month', c.date_start)::date,
count(*) 
from customer
question from:https://stackoverflow.com/questions/65873096/is-there-a-sql-code-for-cumulative-count-of-saas-customer-over-months

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please check next solution:

select 
    subscrubed_date,
    subscrubed_customers,
    unsubscrubed_customers,
    coalesce(subscrubed_customers, 0) - coalesce(unsubscrubed_customers, 0) cumulative
from (
    select distinct
    date_trunc('month', c.date_start)::date subscrubed_date,
    sum(1) over (order by date_trunc('month', c.date_start)) subscrubed_customers
    from customer c
    order by subscrubed_date
) subscribed
left join (
    select distinct
    date_trunc('month', c.date_end)::date unsubscrubed_date,
    sum(1) over (order by date_trunc('month', c.date_end)) unsubscrubed_customers
    from customer c
    where date_end is not null
    order by unsubscrubed_date
) unsubscribed on subscribed.subscrubed_date = unsubscribed.unsubscrubed_date;

share SQL query


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...