178. Rank Scores
1、题目与答案
Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no “holes” between ranks.
编写SQL查询对分数进行排序。如果两个分数相等,则两者应具有相同的排名。请注意,在相等之后,下一个排名数应该是下一个连续的整数值。换句话说,相等的分数并列。
Table:Scores
+----+-------+
| Id | Score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
For example, given the above
Scores
table, your query should generate the following report (order by highest score):
例如,给定上面的“Scores”表,您的查询应生成以下报告(按最高分数排序)
+-------+------+
| Score | Rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+
答案:
select
Score,
(select count(distinct b.Score) from scores b where b.Score >= s.Score) as Rank
from scores s
order by Score desc
2、 知识点总结
验证步骤:
创建并插入表scores
create table scores(
Id int NULL,
Score double NULL
);
insert into scores
values(1,3.5),(2,3.65),(3,4.00),(4,3.85),(5,4.00),(6,3.65);
执行答案可得:
+-------+------+
| Score | Rank |
+-------+------+
| 4 | 1 |
| 4 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.5 | 4 |
+-------+------+
6 rows in set (0.00 sec)
知识点:
- 子查询与where筛选
select count( distinct id ) from table_name
计算talbebname表中id不同的记录有多少条