From 93ae8af223a66b83d75e37b0076d9a76c8c055f1 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 19 Feb 2026 14:31:52 +0300 Subject: [PATCH] PET 4th task completed --- aharlamcev/postgresql/Pet-projectsql.sql | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/aharlamcev/postgresql/Pet-projectsql.sql b/aharlamcev/postgresql/Pet-projectsql.sql index bc21d74..1fb75f6 100644 --- a/aharlamcev/postgresql/Pet-projectsql.sql +++ b/aharlamcev/postgresql/Pet-projectsql.sql @@ -289,5 +289,38 @@ ROUND(1.00 * total_views / total_lessons, 2) as avg_views_per_lesson from total_counts ; +----------------------------------------------------------------------------------------------------- +-- 4 Задание Когортный анализ пользователей +create materialized view user_cohort_analysis AS +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, + e.user_id as enrolled_users, + lv.user_id as active_users + 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 enrolled_users) as enrolled_users, + COUNT(distinct active_users) 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 + where date_trunc('month', reg_date)::date = '2023-03-01' + 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 / users_in_cohort as avg_courses_per_user, +avg_time_to_first_view +from CTE +; +