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.

+----+-------+
| Id | Score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
For example, given the above Scores table, your query should generate the following report (order by highest score): +-------+------+
| Score | Rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+

此题,其本质就是赋值行号(需要注意分数相同的情景).

在实践过程中,初版答案如下所示:

# Write your MySQL query statement below
SELECT
a.Score AS Score,
(SELECT COUNT(DISTINCT b.Score) FROM Scores b where b.Score >= a.Score) AS Rank
FROM Scores a ORDER BY a.Score DESC;

此处,使用select count来统计行号,注意使用distinct来区分相同分数.

但是,此解题方案的效率较差,sql运行肯定是越快越好.

因此,在sql中引入变量来赋值行号,以替代耗时的select count操作.

# Write your MySQL query statement below
SELECT
Score,
@row := @row + (@pre <> (@pre := Score)) AS Rank
FROM Scores, (SELECT @row := 0, @pre := -1) t
ORDER BY Score DESC;

此处,查询是在Scores与临时表之间进行cross join.

此外,使用临时变量(@row,@pre)记录行号.

Tips:

  • 通过@pre与当前Score的比较,确定是否+1,需要注意mysql中的true/false0/1);
  • sql中,set/update语句中,=表示赋值;在set/update/select中,:=表示赋值,因此使用:=.

通过以上改进,mysql的运行效率得到了较大的提高.

PS:

如果您觉得我的文章对您有帮助,请关注我的微信公众号,谢谢!

最新文章

  1. H3 BPM社区:流程开发者的学习交流平台
  2. 2016 Google code jam 答案
  3. Java——不弹起的按钮组件:JToggleButton
  4. Linux Shell常用快捷键
  5. 使用 Laravel 框架:成为微信公众平台开发者
  6. Cocos2d-x——CocosBuilder官方帮助文档翻译3 动画
  7. 使用C# 实现文件锁
  8. Hibernate-Validation的使用
  9. PYTHON queue
  10. Ubuntu下比较通用的makefile实例
  11. &lt;%@include file=&quot;a.jsp&quot;%&gt; jsp引用jsp文件时候注意
  12. Struts优缺点
  13. 使用datagrid时json的格式
  14. 局部变量,全局变量初始值问题----C与指针练习题4.14.1
  15. leetcode — spiral-matrix-ii
  16. springBoot系列--&gt;springBoot注解大全
  17. jQuery源码分析学习--资料收集--更新中
  18. 从javaScript中学习正则表达式——RegExp
  19. _pvp
  20. Bzoj2673 3961: [WF2011]Chips Challenge 费用流

热门文章

  1. Spring Boot2.1.7启动zipkin-server报错:Error creating bean with name &#39;armeriaServer&#39; defined in class path
  2. python基础 while 字符串方法 运算符
  3. mysql connector c++ 1.1 API初步体验
  4. 简单的shell脚本
  5. 4.Python网络编程_一般多线程创建步骤
  6. Python学习笔记3 函数_20170614
  7. 《HBase在滴滴出行的应用场景和最佳实践》
  8. Ubuntu下的录GIF神器——Peek
  9. luoguP2178 [NOI2015]品酒大会(后缀数组做法)
  10. luoguP2852 [USACO06DEC]Milk Patterns