풀다가 몇가지 까먹었던 개념을 다시 잡으면 좋을 것 같아서 써보려고 한다.
오늘 풀었던 1341. Movie Rating 문제는 아래와 같다
Table: Movies
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| movie_id | int |
| title | varchar |
+---------------+---------+
movie_id is the primary key for this table.
title is the name of the movie.
Table: Users
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| user_id | int |
| name | varchar |
+---------------+---------+
user_id is the primary key for this table.
Table: MovieRating
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| movie_id | int |
| user_id | int |
| rating | int |
| created_at | date |
+---------------+---------+
(movie_id, user_id) is the primary key for this table.
This table contains the rating of a movie by a user in their review.
created_at is the user's review date.
Write an SQL query to:
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.
The query result format is in the following example.
처음에는 서브쿼리를 사용하다가 너무 복잡해지는 것 같아서 찬찬히 생각해보았다.
어짜피 구해야하는 대상이 2개가 다른 것이라서 따로따로 구해서 UNION으로 합쳐야겠다고 생각했다.
그런데 처음에 영어 문제 해석을 잘못해서 산으로 가다가 30분 만에 파파고 돌려보고 잘못됨을 느꼈다ㅠㅠ
SQL 풀려면 영어도 잘해야하는 현실....🥹
암튼 이번 문제는 각각 문제의 답을 구해서 results로 컬럼명 일치 시키고 결합하는 식으로 풀었다.
(
SELECT title AS results
FROM MovieRating MR
LEFT JOIN Users U ON MR.user_id = U.user_id
LEFT JOIN Movies M ON MR.movie_id = M.movie_id
WHERE DATE_FORMAT(created_at,'%Y-%m') = '2020-02'
GROUP BY M.movie_id
ORDER BY AVG(rating) DESC, title ASC
LIMIT 1
)
UNION ALL
(
SELECT name AS results
FROM MovieRating MR
LEFT JOIN Users U ON MR.user_id = U.user_id
LEFT JOIN Movies M ON MR.movie_id = M.movie_id
GROUP BY MR.user_id
ORDER BY COUNT(MR.user_id) DESC, name ASC
LIMIT 1
)
오늘의 배운점 !
💡 ORDER BY 절에서 AVG, SUM 등 사용 가능하니, SELECT에 보여줘야 하는 거 아니면 이렇게도 사용하자
💡중복값을 제외하라는 예외사항이 없다면 일단은 UNION ALL로 사용해보자 !
'SQL' 카테고리의 다른 글
[MYSQL] 값의 형변환을 해주는 CAST 함수 (0) | 2023.10.14 |
---|---|
리트코드 1204. Last Person to Fit in the Bus (0) | 2023.08.08 |
리트코드(LeetCode) 1211. Queries Quality and Percentage (0) | 2023.07.13 |
리트코드(LeetCode) 197. Rising Temperature (0) | 2023.07.12 |
데이터를 원하는 형식으로 배열하기 : GROUP_CONCAT (0) | 2023.06.29 |