Table: Movies
Column Name | Type |
---|---|
movie_id | int |
title | varchar |
movie_id is the primary key (column with unique values) 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 (column with unique values) for this table.
The column 'name' has unique values.
Table: MovieRating
Column Name | Type |
---|---|
movie_id | int |
user_id | int |
rating | int |
created_at | date |
(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:
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_id | title |
---|---|
1 | Avengers |
2 | Frozen 2 |
3 | Joker |
Users
table:
user_id | name |
---|---|
1 | Daniel |
2 | Monica |
3 | Maria |
4 | James |
MovieRating
table:
movie_id | user_id | rating | created_at |
---|---|---|---|
1 | 1 | 3 | 2020-01-12 |
1 | 2 | 4 | 2020-02-11 |
1 | 3 | 2 | 2020-02-12 |
1 | 4 | 1 | 2020-01-01 |
2 | 1 | 5 | 2020-02-17 |
2 | 2 | 2 | 2020-02-01 |
2 | 3 | 2 | 2020-03-01 |
3 | 1 | 3 | 2020-02-22 |
3 | 2 | 4 | 2020-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 으로 표시한다.