我是靠谱客的博主 虚幻月光,最近开发中收集的这篇文章主要介绍Rank Scores,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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.

+----+-------+
| 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):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

题意:

就是对成绩进行排序,但需要注意的是,相同值的排名相同,而且排名还能有漏掉的排序数。如上表中的3.85是2而不是3

解法一:

# Write your MySQL query statement below
SELECT Scores.Score, COUNT(Ranking.Score) AS RANK
  FROM Scores
     , (
       SELECT DISTINCT Score
         FROM Scores
       ) Ranking
 WHERE Scores.Score <= Ranking.Score
 GROUP BY Scores.Id
 ORDER BY Scores.Score DESC;

这是利用了笛卡尔积,然后在进行统计。

解法二

使用MySQL的用户定义变量。

# Write your MySQL query statement below
SELECT Score, Rank FROM(
  SELECT    Score,
            @curRank := @curRank + IF(@prevScore = Score, 0, 1) AS Rank, @prevScore := Score
  FROM      Scores s, (SELECT @curRank := 0) r, (SELECT @prevScore := NULL) p
  ORDER BY  Score DESC
) t;


转自:http://www.tuicool.com/articles/rYb6nyU




最后

以上就是虚幻月光为你收集整理的Rank Scores的全部内容,希望文章能够帮你解决Rank Scores所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部