Count active customers dependent on start and end date
Customer Start Date End Date
1 2020-01 2020-04
2 2020-01 2020-03
3 2020-02
Hi, I have a table like the above. I would like to calculate the number of "Active Customers" for each month. Sometimes we have an "End Date" and sometimes we don’t (then they are still active).
So for the Example above, I would like an output like this:
on 2020-01: Number of Active Customers = 2 (Customer 1 + 2)
on 2020-02: Number of Active Customers = 3(Customer 1 + 2 + 3)
on 2020-03: Number of Active Customers = 3 (Customer 1 + 2 + 3)
on 2020-04: Number of Active Customers = 2 (Customer 1 + 3)
on 2020-05: Number of Active Customers = 1 (Customer 3)
2020-06: Number of Active Customers = 1 (Customer 3)
Thanks
2
Answers
Generate a calendar and then
OUTER JOIN
to the table with customer data and aggregate for each month:Which, for the sample data:
Outputs:
fiddle
Split the customer table in two sources, one representing the new customers (with Start_Date), the second the churned customers (with End_Date) and
union all
the two sources (first CTE in teh example).Group it on the transaction date and sum the count (2nd CTE).
Finally calculate the cummulated count (main query using aggregated function)
Example
Of course if you want to see the figured for months without customer movement (here 5+6/2020) you must use the trick with calendar and outer join as proposed in alternative answer.