-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3_retention_analysis.sql
More file actions
38 lines (36 loc) · 1.1 KB
/
3_retention_analysis.sql
File metadata and controls
38 lines (36 loc) · 1.1 KB
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
33
34
35
36
37
WITH last_purchase_date as (
SELECT
customerkey,
cleaned_name,
orderdate,
row_number() over(PARTITION BY customerkey ORDER BY orderdate DESC) AS rn,
cohort_year,
first_purchase_date
FROM cohort_analysis
),
customer_statuses AS (
SELECT
cohort_year,
customerkey,
cleaned_name,
orderdate AS last_purchased_date,
first_purchase_date,
CASE
WHEN orderdate < ((SELECT MAX(orderdate) FROM sales) - INTERVAL '6 months') THEN 'churned'
ELSE 'active'
END customer_status
FROM last_purchase_date
WHERE
rn = 1 AND
first_purchase_date < ((SELECT MAX(orderdate) FROM sales) - INTERVAL '6 months')
)
SELECT
cohort_year,
customer_status,
count(customer_status) AS count_of_status,
SUM(count(customer_status)) OVER(PARTITION BY cohort_year) AS total_customers,
round(100*(count(customer_status)/SUM(count(customer_status)) OVER(PARTITION BY cohort_year)),2) AS percent_of_customers
FROM customer_statuses
GROUP BY
cohort_year,
customer_status;