리트코드(leetcode) 문제풀이 : Movie Rating (10/10)

백엔ㄷ현·2024년 10월 10일
0

Table: Movies

Column NameType
movie_idint
titlevarchar

movie_id is the primary key (column with unique values) for this table.
title is the name of the movie.

Table: Users

Column NameType
user_idint
namevarchar

user_id is the primary key (column with unique values) for this table.
The column 'name' has unique values.

Table: MovieRating

Column NameType
movie_idint
user_idint
ratingint
created_atdate

(movie_id, user_id) is the primary key (column with unique values) 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 a solution 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 result format is in the following example.

Example 1:

Input:
Movies table:

movie_idtitle
1Avengers
2Frozen 2
3Joker

Users table:

user_idname
1Daniel
2Monica
3Maria
4James

MovieRating table:

movie_iduser_idratingcreated_at
1132020-01-12
1242020-02-11
1322020-02-12
1412020-01-01
2152020-02-17
2222020-02-01
2322020-03-01
3132020-02-22
3242020-02-25

Output:

results
Daniel
Frozen 2

Explanation:
Daniel and Monica have rated 3 movies ("Avengers", "Frozen 2" and "Joker") but Daniel is smaller lexicographically.
Frozen 2 and Joker have a rating average of 3.5 in February but Frozen 2 is smaller lexicographically.


요구 사항이 두개인 특이한 문제였다. 요구 사항이 두개라 union all 을 사용하여 각각의 쿼리를 하나의 output 으로 조회할 수 있는 문제였다. 쿼리 자체는 어렵지 않았다.

-- 1. 첫 번째 요구사항 : 가장 많은 영화를 평가한 사용자 찾기
(select u.name as results
from users u
inner join movierating mr
	on u.user_id = mr.user_id
group by u.name
order by count(mr.movie_id) desc, u.name
limit 1)

union all

-- 2. 두 번째 요구사항 : 2020년 2월에 최고 평균 평점을 받은 영화 찾기
(select m.title as results
from movies m
inner join movierating mr
	on m.movie_id = mr.movie_id
where mr.created_at between '2020-02-01' and '2020-02-29'
group by m.title
order by avg(mr.rating) desc, m.title
limit 1);
  • 1번 쿼리 :
    movierating 테이블에서 user_id 별로 평가한 영화의 수를 조회한다. 그 다음 가장 많은 영화를 평가한 사람을 찾고, 그 수가 같을 경우 이름으로 정렬하여ㅓ 첫 번째 사람을 limit 1 로 조회한다.,

  • 2번 쿼리 :
    where 조건 절로 2020년 2월의 영화만 조회한다. 각 영화의 평균 평점을 avg 함수로 계산하여 limit 1 로 첫 번째 영화 제목을 조회한다.

  • union all :
    작성된 두 쿼리를 합쳐서 output 으로 표시한다.

profile
매일매일 공부한 내용과 코드 기록하겠습니다

0개의 댓글