[1341#_MEDIUM] Movie Rating

2022. 8. 5. 01:28·SQL/LeetCode

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.

 

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.

 

문제 조건 

가장 많은 영화를 평가한 사용자의 이름을 찾으시오.

평가된 영화의 수가 동일할 경우 사전순으로 더 작은 사용자의 이름을 반환합니다. 2020년 2월 평균 평점이 가장 높은 영화의 이름을 찾으시오.평점이 동일할 경우, 사전순으로 더 작은 영화의 이름을 반환합니다.

 

문제 풀이 -- 문제 조건을 똑바로 보자 ^^; 

with temp_1 as (
        select name as results,
                max(movie_id),
                count(movie_id) as cnt
        from MovieRating m
            left join Users u on m.user_id = u.user_id
        group by 1
        order by cnt desc, results
        limit 1),

temp_2 as (
        select title as results,
                max(m.movie_id),
                avg(rating) as avg_rate
        from MovieRating r
            left join Movies m on r.movie_id = m.movie_id
        where created_at >= '2020-02-01' and created_at < '2020-03-01'
        group by 1 
        order by avg_rate desc, results
        limit 1)
        
select results
from temp_1

union

select results
from temp_2

 

저작자표시 (새창열림)

'SQL > LeetCode' 카테고리의 다른 글

[1965_EASY] Employees With Missing Information  (0) 2022.08.07
[1939#_EASY] Users That Actively Request Confirmation Messages  (0) 2022.08.07
[1321#_MEDIUM] Restaurant Growth  (0) 2022.08.05
[1890_EASY] The Latest Login in 2020  (0) 2022.08.05
[1873_EASY] Calculate Special Bonus  (0) 2022.08.04
'SQL/LeetCode' 카테고리의 다른 글
  • [1965_EASY] Employees With Missing Information
  • [1939#_EASY] Users That Actively Request Confirmation Messages
  • [1321#_MEDIUM] Restaurant Growth
  • [1890_EASY] The Latest Login in 2020
소금깨
소금깨
  • 소금깨
    고군분투 인생살이
    소금깨
  • 전체
    오늘
    어제
    • 분류 전체보기 (328)
      • SQL (271)
        • 프로그래머스 (27)
        • LeetCode (198)
        • Hacker Rank (27)
        • Solve SQL (1)
        • 개념 (15)
      • 데이터 분석 (16)
        • 참고하며 공부하기 (14)
      • 기타 (15)
        • 통계 (14)
      • 오류 (6)
      • 인생살이 (0)
        • 리뷰 (0)
        • 일기 (0)
      • 中文 (0)
      • TABLEAU (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    HACKER_RANK
    group by
    LeetCode
    해커랭크
    파이썬을활용한시계열데이터분석AtoZ올인원패키지Online
    패캠챌린지
    프리미엄
    시계열데이터분석
    SQL
    패스트캠퍼스
    프로그래머스
    패스트캠퍼스후기
    MySQL
    easy
    medium
    직장인인강
    직장인자기계발
    파이썬을활용한시계열데이터분석
    Hard
    solvesql
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
소금깨
[1341#_MEDIUM] Movie Rating
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.