Back to Editor

Solution: 47. Top 3 Most Viewed Videos Within Each Channel

Hard

Problem Detail:

Write a SQL query to find the top 3 most viewed videos for each channel.

Answer SQL Query:

WITH ranked_videos AS (
    SELECT c.channel_name,
           v.video_id,
           v.title,
           s.view_count,
           ROW_NUMBER() OVER (
               PARTITION BY v.channel_id
               ORDER BY s.view_count DESC
           ) AS rn
    FROM channels c
    JOIN videos v
      ON c.channel_id = v.channel_id
    JOIN video_stats s
      ON v.video_id = s.video_id
)
SELECT channel_name, video_id, title, view_count
FROM ranked_videos
WHERE rn <= 3;
You can easily copy this solution, switch back to your editor tab, paste it, and run the SQL!