-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3_retention_analysis.sql
More file actions
32 lines (32 loc) · 933 Bytes
/
Copy path3_retention_analysis.sql
File metadata and controls
32 lines (32 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
WITH customer_last_purchase AS (
SELECT
customerkey,
cleaned_name,
orderdate,
ROW_NUMBER() OVER (PARTITION BY customerkey ORDER BY orderdate DESC) AS rn,
first_purchase_date,
cohort_year
FROM
cohort_analysis
), churned_customers AS (
SELECT
customerkey,
cleaned_name,
orderdate AS last_purchase_date,
CASE
WHEN orderdate < (SELECT MAX(orderdate) FROM sales) - INTERVAL '6 months' THEN 'Churned'
ELSE 'Active'
END AS customer_status,
cohort_year
FROM customer_last_purchase
WHERE rn = 1
AND first_purchase_date < (SELECT MAX(orderdate) FROM sales) - INTERVAL '6 months'
)
SELECT
cohort_year,
customer_status,
COUNT(customerkey) AS num_customers,
SUM(COUNT(customerkey)) OVER(PARTITION BY cohort_year) AS total_customers,
ROUND(COUNT(customerkey) / SUM(COUNT(customerkey)) OVER(PARTITION BY cohort_year), 2) AS status_percentage
FROM churned_customers
GROUP BY cohort_year, customer_status