DROP MATERIALIZED VIEW IF EXISTS dm.lesson_popularity_summary; CREATE MATERIALIZED VIEW dm.lesson_popularity_summary DISTRIBUTED BY (lesson_id) AS select t1.lesson_id as lesson_id, dl.title as lesson_title, t1.course_id as course_id, dc.title as course_title, t1.total_views as total_views, t1.unique_users as unique_users, t1.first_view as first_view, t1.last_view as last_view from (select flv.lesson_id, flv.course_id, COUNT(*) as total_views, COUNT(distinct flv.user_id) as unique_users, MIN(flv.viewed_at) as first_view, MAX(flv.viewed_at) as last_view from core.fact_lesson_views flv group by flv.lesson_id, flv.course_id ) as t1 right join core.dim_lesson dl on dl.lesson_id = t1.lesson_id left join core.dim_course dc on t1.course_id = dc.course_id;