美文网首页
[leetCode]分数排名

[leetCode]分数排名

作者: L_800d | 来源:发表于2018-12-25 21:30 被阅读0次

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

    解决方法一:

    /*此处as Rank会报错  应该是因为Rank为关键字*/
    select Score,(select count(DISTINCT Score) from Scores where Score >= s.Score) as Rank
    from Scores s
    order by Score desc;
    

    DISTINCT的用法

    在使用MySQL时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录,但是实际中我们往往用distinct来返回不重复字段的条数(count(distinct id)),其原因是distinct只能返回他的目标字段,而无法返回其他字段

    相关文章

      网友评论

          本文标题:[leetCode]分数排名

          本文链接:https://www.haomeiwen.com/subject/hkmqlqtx.html