• LeetCode(数据库):分数排名


    Create table If Not Exists Scores (Id int, Score DECIMAL(3,2));
    Truncate table Scores;
    insert into Scores (Id, Score) values ('1', '3.5');
    insert into Scores (Id, Score) values ('2', '3.65');
    insert into Scores (Id, Score) values ('3', '4.0');
    insert into Scores (Id, Score) values ('4', '3.85');
    insert into Scores (Id, Score) values ('5', '4.0');
    insert into Scores (Id, Score) values ('6', '3.65');

    编写一个 SQL查询 来实现分数排名。如果两个分数相同,则两个分数排名(Rank)应该相同。请注意,平局之后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“漏洞”。

    +----+-------+
    | Id | Score |
    +----+-------+
    | 1  | 3.50  |
    | 2  | 3.65  |
    | 3  | 4.00  |
    | 4  | 3.85  |
    | 5  | 4.00  |
    | 6  | 3.65  |
    +----+-------+
    

    例如,根据给定的上述 Scores 表,您的查询应该生成以下报告(按最高分排序):

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

     第一种解决方法:This one counts, for each score, the number of distinct greater or equal scores.(每条数据循环,求和这个数据相等或者大的个数)

    SELECT
      Score,
      (SELECT count(distinct Score) FROM Scores WHERE Score >= s.Score) Rank
    FROM Scores s
    ORDER BY Score desc

    第二种:与前一个相同,但更快,因为我有一个子查询“首先独立”分数。不完全确定为什么它更快,我猜MySQL做tmp了一个临时表,并将它用于每个外部分数。

    SELECT
      Score,
      (SELECT count(*) FROM (SELECT distinct Score s FROM Scores) tmp WHERE s >= Score) Rank
    FROM Scores
    ORDER BY Score desc

    第三种:

    SELECT s.Score, count(distinct t.score) Rank
    FROM Scores s JOIN Scores t ON s.Score <= t.score
    GROUP BY s.Id
    ORDER BY s.Score desc
  • 相关阅读:
    分析SIX锁和锁分区导致的死锁
    导数中的最小化日志记录:测试和分析
    导数中的最小化日志记录:背景和理论
    Redis学习笔记(十一) 服务器
    Redis学习笔记(十) 客户端
    Redis学习笔记(九) AOF持久化
    Redis学习笔记(八) RDB持久化
    Redis学习笔记(七) 数据库
    Redis学习笔记(六) 对象
    Redis学习笔记(五) 压缩列表
  • 原文地址:https://www.cnblogs.com/lxl57610/p/8658435.html
Copyright © 2020-2023  润新知