zoukankan      html  css  js  c++  java
  • LeetCode-178:分数排名

    题目描述:

    编写一个 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    |
    +-------+------+

    SQL架构:

    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');

    解题思路:

      oracle可以使用排名函数进行排名,因为名次之间不应该有“间隔”,所以要使用dense_rank()函数,这个函数排的名次是连续的,rank()函数会跳过(并列排名),mysql依然是使用自定义变量来进行排名。

    解题方案:

      oracle

    select round(a.score,2) as score, b.rank
      from Scores a
      join (select a.*, rownum as rank
              from (select distinct a.score from Scores a order by a.score desc) a) b
        on a.score = b.score
     order by b.rank

      mysql

    SELECT
        ROUND(a.score, 2) AS score,
        b.rank
    FROM
        Scores a
    JOIN (
        SELECT
            a.*, (@rowNum :=@rowNum + 1) AS rank
        FROM
            (
                SELECT DISTINCT
                    a.score
                FROM
                    Scores a
            ) a,
            (SELECT(@rowNum := 0)) b
        ORDER BY
            a.score DESC
    ) b ON a.score = b.score
    ORDER BY
        b.rank
  • 相关阅读:
    Django WSGI响应过程之WSGIHandler
    python多线程
    性能测试概念介绍
    Django惰性加载和LazyObject
    Django中间件分析
    python unittest 快速入门
    jenkins+ant+jmeter测试环境部署
    [Vue warn]: Invalid prop: type check failed for prop "clearable". Expected Boolean, got String with value "true".
    JavaScript通过for循环实现九九乘法表的左下、左上、右上、右下对齐成直角三角形
    找出正确手机号码
  • 原文地址:https://www.cnblogs.com/zouqf/p/10283410.html
Copyright © 2011-2022 走看看