SQL
코테 준비 | Movie Rating (JOIN,UNION ALL)
성장하는 쿠키의 로그 기록
2025. 1. 9. 10:11
☑️ 1341. Movie Rating
[문제]
- Find the name of the user who has rated the greatest number of movies. In case of a tie, return the lexicographically smaller user name.
- Find the movie name with the highest average rating in February 2020. In case of a tie, return the lexicographically smaller movie name.
- 두 가지 조건에 해당하는 출력값 각각 집계후 합쳐주기 ( UNION 사용)
[문제 풀이]
내 코드
(SELECT u.name AS results-- 각각에서 찾아주고, 출력값 연결해주는 아이디어
FROM movierating mo
INNER JOIN users u on u.user_id = mo.user_id
GROUP BY mo.user_id,u.name
HAVING COUNT(distinct mo.movie_id)
ORDER BY COUNT(distinct mo.movie_id) DESC,u.name
LIMIT 1)
UNION ALL
(SELECT m.title AS results-- 각각에서 찾아주고, 출력값 연결해주는 아이디어
FROM movierating mo
INNER JOIN movies m on m.movie_id = mo.movie_id
WHERE DATE_FORMAT(mo.created_at,'%Y-%m') = '2020-02'
GROUP BY mo.movie_id
HAVING AVG(mo.rating)
ORDER BY AVG(mo.rating) DESC, m.title
LIMIT 1)
이슈 및 해결 과정
- `아이디어` : 각각의 조건에 맞는 테이블 조인 & 집계 후 출력값 UNION 으로 연결
- 조건1) 가장 많은 영화에 평점을 준 평가자 이름 조회
- movierating 과 users 테이블 join → 한 후 order by 로 가장 많은 값 - 이름 순 정렬 , 최종 1개 이름 출력
- 조건2) 2020-02월에 평균 점수가 가장 높은 영화 이름 조회
- movierating 과 movies 테이블 join →order by로 평균이 가장 높은값 - 제목순 정렬, 최종 1개 이름 출력
- 연결 ) union all 사용하여 연결
- 주의 : 각각 출력값 조회 쿼리에 소괄호 필수, 안해주시면 조건별 정렬이 안됨
한줄 포인트
- 정렬조건&제한조건이 있는 테이블간의 행 연결 (union )시 소괄호 필수