Good job! We already know how many churned customers there are in each registration cohort. However, we would like to compare the number of churned customers to the total number of customers in a given registration cohort. How can we do that? Let's look:
SELECT
DATEPART(Year, RegistrationDate) AS Year,
DATEPART(Week, RegistrationDate) AS Week,
COUNT(CustomerID) AS AllCustomers,
COUNT(CASE WHEN DATEDIFF(Day, LastOrderDate, GETDATE()) > 30 THEN CustomerID END) AS ChurnedCustomers,
COUNT(CASE WHEN DATEDIFF(Day, LastOrderDate, GETDATE()) > 30 THEN CustomerID END) * 100.0 / COUNT(CustomerID) AS ChurnedPercentage
FROM Customers
GROUP BY
DATEPART(Year, RegistrationDate),
DATEPART(Week, RegistrationDate)
ORDER BY
DATEPART(Year, RegistrationDate),
DATEPART(Week, RegistrationDate);
As you can see, we used COUNT(CustomerID)
to count all the customers in a given cohort. Then we used COUNT(CASE WHEN ...)
to include only customers that placed an order no later than 30 days ago.
Next, we calculated the percentage of churned customers in the cohort by dividing the number of churned customers by the number of all customers. Note that we multiplied the numerator by 100.0
(a float) and not 100
(an integer) to avoid integer division.