LeetCode //MySQL - 178. Rank Scores

178. Rank Scores

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 |
±------±-----+

From: LeetCode
Link: 178. Rank Scores


Solution:

Ideas:
  1. SELECT score: Selects the score column from the Scores table.
  2. DENSE_RANK() OVER (ORDER BY score DESC) AS rank: The DENSE_RANK() function is used here. The OVER (ORDER BY score DESC) clause specifies that the ranking should be done in descending order of the scores. The result of this ranking is labeled as rank.
  3. FROM Scores: Specifies the table to retrieve the data from.
  4. ORDER BY score DESC: Orders the final result by the score in descending order.
Code:
SELECT 
    score,
    DENSE_RANK() OVER (ORDER BY score DESC) AS `rank`
FROM 
    Scores
ORDER BY 
    score DESC;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值