본문 바로가기
SQL/코딩테스트

[leetcode / MySQL] 178. Rank Scores

by Hi_heidi 2024. 2. 1.

문제

💡 Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:

  • The scores should be ranked from the highest to the lowest.
  • If there is a tie between two scores, both should have the same ranking.
  • After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.

Return the result table ordered by score in descending order.

 

테이블 형태

 

풀이

SELECT *
FROM (SELECT score
            , DENSE_RANK() OVER(ORDER BY score DESC) 'rank'
        FROM Scores) scores

 

해설

SELECT *
FROM (SELECT score
            , DENSE_RANK() OVER(ORDER BY score DESC) 'rank'
        FROM Scores) scores
  • 다음 조건을 만족시키는 순위를 매겨야 한다 :
    1. 높은 점수가 높은 순위일 것
    2. 동점이면 동일 순위 부여할 것
    3. 동점 이후 랭킹은 바로 다음 숫자를 부여, 즉 빠지는 숫자가 없을 것
  • 점수를 기준으로 내림차순 정렬 후 빽빽하게 랭킹을 매기는 DENSE_RANK로 순위를 매겨야 한다(leetcode 511. Game Play Analysis1 풀이 중 RANK, DENSE_RANK, ROW_NUMBER 차이 참고)
  • FROM절 서브쿼리에서 이미 score를 기준으로 내림차순 정렬해 순위를 매겼기 때문에 메인쿼리에서 ORDER BY를 해주지 않아도 된다
 

[leetcode / MySQL] 511. Game Play Analysis1

문제 💡 Write a solution to find the first login date for each player. Return the result table in any order. 테이블 형태 풀이 SELECT player_id, first_login FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY event_date) AS row_n , p

hei-ground.tistory.com