Repository navigation
Expand file tree
/
Copy pathCustomer_Retention_Analysis.sql
More file actions
61 lines (60 loc) · 1.99 KB
/
Copy pathCustomer_Retention_Analysis.sql
File metadata and controls
61 lines (60 loc) · 1.99 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
-- Weekly customer purchase retention
-- Cohort = first observed qualifying purchase week, not account signup.
-- Monday-based calendar weeks; exclude the final incomplete week.
WITH Purchases AS (
SELECT customer_id,
TO_TIMESTAMP(invoice_date, 'DD/MM/YYYY HH24:MI')::timestamp AS purchase_date,
invoice_no
FROM online_retail
WHERE customer_id IS NOT NULL
AND quantity > 0
AND unit_price > 0
AND UPPER(invoice_no) NOT LIKE 'C%'
),
Actions AS (
SELECT DISTINCT customer_id,
DATE_TRUNC('week', purchase_date)::date AS event_week
FROM Purchases
),
Signups AS (
SELECT customer_id, MIN(event_week) AS signup_week
FROM Actions
GROUP BY customer_id
),
Cohort AS (
SELECT signup_week, COUNT(*) AS cohort_size
FROM Signups
GROUP BY signup_week
),
Retained AS (
SELECT s.signup_week, a.event_week,
COUNT(DISTINCT a.customer_id) AS retained_customers
FROM Signups s
JOIN Actions a ON s.customer_id = a.customer_id
AND a.event_week >= s.signup_week
GROUP BY s.signup_week, a.event_week
),
Reporting_End AS (
SELECT DATE_TRUNC('week', MAX(purchase_date))::date AS incomplete_week
FROM Purchases
),
Cohort_Weeks AS (
SELECT c.signup_week, c.cohort_size, w.event_week::date AS event_week
FROM Cohort c
CROSS JOIN Reporting_End e
CROSS JOIN LATERAL GENERATE_SERIES(
c.signup_week::timestamp,
(e.incomplete_week - 7)::timestamp,
INTERVAL '1 week'
) AS w(event_week)
)
SELECT c.signup_week AS cohort_week,
(c.event_week - c.signup_week) / 7 AS weeks_from_first_purchase,
c.cohort_size,
COALESCE(r.retained_customers, 0) AS retained_customers,
ROUND(100.0 * COALESCE(r.retained_customers, 0) /
NULLIF(c.cohort_size, 0), 2) AS percentage_retained
FROM Cohort_Weeks c
LEFT JOIN Retained r ON c.signup_week = r.signup_week
AND c.event_week = r.event_week
ORDER BY c.signup_week, weeks_from_first_purchase;