SQL Challenge: Movie Rating Query with UNION ALL and Subqueries

🗓️ SQL Challenge Day #37: Movie Rating 🔹 Solve two tricky ranking problems in one query! 🎬 🔹 Problem:   Part 1️⃣: Find user with most ratings (tie-break: lexicographically smaller name)   Part 2️⃣: Find movie with highest avg rating in Feb 2020 (tie-break: lexicographically smaller title)  🔹 Solution (UNION ALL):   (     SELECT u.name AS results     FROM Users u     JOIN (       SELECT user_id, COUNT(user_id) AS c       FROM MovieRating       GROUP BY user_id     ) mr ON u.user_id = mr.user_id     ORDER BY c DESC, u.name ASC     LIMIT 1   )   UNION ALL   (     SELECT m.title AS results     FROM Movies m     JOIN (       SELECT movie_id, AVG(rating) AS r       FROM MovieRating       WHERE DATE_FORMAT(created_at, '%Y-%m') = '2020-02'       GROUP BY movie_id     ) mav ON m.movie_id = mav.movie_id     ORDER BY r DESC, m.title ASC     LIMIT 1   );  ✅ Result: Accepted  💡 Key Takeaway:   **UNION ALL + subqueries** cleanly separates two distinct problems!   ⚠️ Critical details:   - `DATE_FORMAT(created_at, '%Y-%m') = '2020-02'` isolates February   - Dual ordering (`c DESC, name ASC`) handles tie-breaks correctly   - Parentheses around each SELECT are mandatory for LIMIT in UNION  👇 Your turn:   What’s your strategy for handling multi-part SQL problems? Do you always split them like this?  #SQL #LeetCode #DataEngineering #ProblemSolving #Coding #LearningInPublic #Database #DataAnalytics

  • graphical user interface, text, application, chat or text message

To view or add a comment, sign in

Explore content categories