Table: Scores
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| score | decimal |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains the score of a game. Score is a floating point value with two decimal places.
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.
The result format is in the following example.
Example 1:
Input:
Scores table:
+----+-------+
| id | score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
Output:
+-------+------+
| score | rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+
테이블: Scores
+-------------+---------+
| 컬럼 이름 | 타입 |
+-------------+---------+
| id | int |
| score | decimal |
+-------------+---------+
id는 이 테이블의 기본 키(고유한 값을 가지는 컬럼)입니다.
각 행은 게임의 점수를 나타내며, score는 소수점 두 자리까지 있는 실수 값입니다.
문제:
점수의 순위를 구하는 SQL 쿼리를 작성하세요. 순위는 다음 규칙을 따릅니다.
- 점수가 높은 순서대로 순위를 매깁니다.
- 동일한 점수를 가진 경우, 동일한 순위를 가져야 합니다.
- 동일한 순위를 가진 점수 다음 순위는 건너뛰지 않고 연속된 정수 값이어야 합니다.
- 결과는 점수를 기준으로 내림차순으로 정렬해야 합니다.
예제:
입력 (Scores 테이블):
+----+-------+
| id | score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
출력:
+-------+------+
| score | rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+
# 이 문제는 Medium 난이도에 맞지 않게 쉽다.
# 1. 윈도우 함수를 이용하고, 예약어인 rank를 컬럼이름으로 사용하기 위해 백틱으로 감싸주면 된다.
SELECT
score,
DENSE_RANK() OVER(ORDER BY score DESC) AS `rank`
FROM scores
'[SQL]' 카테고리의 다른 글
LeetCode 코딩 테스트 - Friend Requests ll: Who Has the Most Friends(LV.Medium) (0) | 2025.03.06 |
---|---|
LeetCode 코딩 테스트 - Customers Who Bought All Products(LV.Medium) (0) | 2025.03.05 |
LeetCode 코딩 테스트 - Last Person to Fit in the Bus(LV.Medium) (0) | 2025.03.02 |
LeetCode 코딩 테스트 - Exchange Seats(LV.Medium) (0) | 2025.03.02 |
LeetCode 코딩 테스트 - Tree Node(LV.Medium) (0) | 2025.02.28 |