[LeetCode]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.

IdScore
13.50
23.65
34.00
43.85
54.00
63.65

For example, given the above Scores table, your query should generate the following report (order by highest score):

ScoreRank
4.001
4.001
3.852
3.653
3.653
3.504

思路

官方讨论里需要用到MYSQL的用户自定义变量了,但是我没用哈,我用的是笛卡尔乘积。


笛卡尔乘积

笛卡尔乘积其实就是两个表的级联,所以接下来我分析一下具体的步骤:

  1. 选择所有不重复的Score数据,组成新表s2。
(select distinct Score from Scores) as s2;
  1. 级联Scores表和s2表,级联的条件是Scores表的Score字段值小于等于s2表Score字段的值。
select * from Scores as s1 left join (select distinct Score from Scores) as s2 on s1.Score <= s2.Score;

这样级联后,生成的新表内容如下:

s1.Scoreids2.Score
3.513.5
3.513.65
3.513.85
3.514.0
3.6523.65
3.6523.85
3.6524
434

这里只举了前三个数据的例子,通过这个临时表,其实我们应该已经能得出解决思路了。我们接下来,可以通过先用id字段做聚集,然后使用count(s2.Score)的数量作为Rank字段。

  1. 排序数据(AC SQL)。
select s1.Score as Score, count(s2.Score) as Rank from Scores as s1 left join (select distinct Score from Scores) as s2 on s1.Score <= s2.Score group by s1.id order by s1.Score desc;

用户自定义变量


自定义变量概述

用户自定义的变量可以先在用户变量中保存值,然后再以后引用它。这样,可以将值从一个语句传递到另一个语句。用户变量与连接有关,也就是说,一个客户端定义的变量不能被其它客户端看到或使用。当客户端退出时,该客户端连接的所有变量都将自动释放。


自定义变量语法

在select语句中赋值给用户变量的语法是:@var_name := value,这里的var_name是变量名,value是你正在检索的值。


AC SQL

select Score, Rank from (
select Score, @curRank := @curRank + IF(@prevScore = Score, 0, 1) as Rank, @prevScore := Score from
Scores as s, (select @curRank := 0) as r, (select @prevScore := NULL) as p
order by Score DESC
) as t;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值