1. 程式人生 > >Mysql分數排名(連續值)

Mysql分數排名(連續值)

1.構建一張表 

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');
-- 查詢去重後分數的,條件:當前行分數大於等於同表的分數的count數量,去重顯示,然後降序輸出
select Score, (select count(distinct Score) from Scores where Score>=s.Score) 
as Rank from Scores as s order by Score desc;  
-- 首先查詢去重後的分數作為新表,使用count統計行,
-- 條件:當前去重表後的分數>=未去重的分數作為Rank的引數,然後使用排序降序輸出
select Score,(select count(*) from (select distinct Score as s from Scores)
as new_scores where s >= Score) Rank from Scores order by Score desc;

# Write your MySQL query statement below
select Score,
(select count(distinct Score) from Scores where Score>=s.Score) Rank
from Scores s  order by Score DESC