Hi @Jennis
Check this query:
;WITH CTE1 AS
(
SELECT YEAR(DateofJoin) AS [YEAR],MONTH(DateofJoin) AS [MONTH],COUNT(DateofJoin) AS [New Customers]
FROM Customers
GROUP BY YEAR(DateofJoin),MONTH(DateofJoin)
),CTE2 AS
(
SELECT YEAR(CustomerCancelDate) AS [YEAR],MONTH(CustomerCancelDate) AS [MONTH],COUNT(CustomerCancelDate) AS [New Churn]
FROM Customers
WHERE CustomerCancelDate IS NOT NULL
GROUP BY YEAR(CustomerCancelDate),MONTH(CustomerCancelDate)
),CTE3 AS
(
SELECT C1.YEAR,C1.MONTH,C1.[New Customers],C2.[New Churn]
,SUM(C1.[New Customers]-C2.[New Churn])OVER(ORDER BY C1.[YEAR],C1.[MONTH]) AS [Total Customers]
FROM CTE1 C1 JOIN CTE2 C2 ON C1.YEAR=C2.YEAR AND C1.MONTH=C2.MONTH
)
SELECT *,CAST([New Churn]*1.0/LAG([Total Customers])OVER(ORDER BY [YEAR],[MONTH])AS DECIMAL(10,2)) AS [ChurnRate]
FROM CTE3
Output:
Note: The Churn Rate of 2022 Jan is null, because there is no 2021 Dec datas.
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.