-
Notifications
You must be signed in to change notification settings - Fork 0
/
latam_data_scientist_khan_academy.sql
51 lines (48 loc) · 1.33 KB
/
latam_data_scientist_khan_academy.sql
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
WITH monthly_usage AS (
SELECT
user_id,
substr(cast(usage_date as varchar), 1, 7) as usage_yrmonth,
SUM(time_spent) AS total_time_spent
FROM
usage
GROUP BY
1, 2
),
cohort AS (
SELECT
user_id,
substr(cast(registration_date as varchar), 1, 7) as cohort_yrmonth
FROM
users
),
engaged_users AS (
SELECT
user_id,
cohort_yrmonth,
COUNT(DISTINCT(usage_yrmonth)) AS num_engaged_months
FROM
cohort
JOIN monthly_usage
ON cohort.user_id = monthly_usage.user_id
AND monthly_usage.month >= cohort.cohort_yrmonth
WHERE
total_time_spent >= 30
GROUP BY
user_id,
cohort_yrmonth
)
SELECT
cohort_yrmonth,
COUNT(DISTINCT cohort.user_id) AS total_users,
ROUND(COALESCE(SUM(CASE WHEN num_engaged_months >= 1 THEN 1 ELSE 0 END) / COUNT(DISTINCT cohort.user_id)::float * 100, 0), 2) AS m1_retention,
ROUND(COALESCE(SUM(CASE WHEN num_engaged_months >= 2 THEN 1 ELSE 0 END) / COUNT(DISTINCT cohort.user_id)::float * 100, 0), 2) AS m2_retention,
ROUND(COALESCE(SUM(CASE WHEN num_engaged_months >= 3 THEN 1 ELSE 0 END) / COUNT(DISTINCT cohort.user_id)::float * 100, 0), 2) AS m3_retention
FROM
cohort
LEFT JOIN engaged_users
ON cohort.user_id = engaged_users.user_id
AND cohort.cohort_yrmonth = engaged_users.cohort_yrmonth
GROUP BY
1
ORDER BY
1 ASC