From de4a0fa2ec2c560455bdfea071f15d6f513fa21c Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 27 Feb 2026 15:31:56 +0300 Subject: [PATCH] PET task 4 fixed --- aharlamcev/PET-project_task4 | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 aharlamcev/PET-project_task4 diff --git a/aharlamcev/PET-project_task4 b/aharlamcev/PET-project_task4 new file mode 100644 index 0000000..5cb8fcd --- /dev/null +++ b/aharlamcev/PET-project_task4 @@ -0,0 +1,26 @@ +with needed_users as ( + select distinct u.id as user_id, + u.registration_date as reg_date, e.course_id, lv.id as view_id, + lv.lesson_id as viewed_lesson_id, + FIRST_VALUE(lv.viewed_at) over (partition by lv.user_id order by lv.viewed_at) as first_view_date + from users u + left join enrollments e on u.id = e.user_id + left join lesson_views lv on e.user_id = lv.user_id + order by user_id + ), +CTE as ( + select + TO_CHAR(reg_date, 'YYYY-MM') as cohort_month, + COUNT(distinct user_id) as users_in_cohort, + COUNT(distinct case when user_id in (select user_id from enrollments) then user_id end) as enrolled_users, + COUNT(distinct case when user_id in (select user_id from lesson_views) then user_id end) as active_users, + COUNT(course_id) as courses_count, + extract('days' from AVG(first_view_date - reg_date)) as avg_time_to_first_view + from needed_users + group by cohort_month + ) +select cohort_month, users_in_cohort, enrolled_users, active_users, +ROUND(100.0 * active_users / users_in_cohort, 2) as retention_rate, +courses_count::numeric / users_in_cohort as avg_courses_per_user, +avg_time_to_first_view +from CTE