博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode Database3
阅读量:7126 次
发布时间:2019-06-28

本文共 1422 字,大约阅读时间需要 4 分钟。

一、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.

+----+-------+| 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    |+-------+------+ 分析:题意为 编写SQL对分数进行排序。如果两个分数相等,其排名应相同。注意在排名相等的分数之后,下一个排名的数值应该连续。换言之,排名之间不应该有“洞”(跳跃)。 思路:使用mysql的自定义变量。
# Write your MySQL query statement belowselect Score,Rank from (SELECT Score,       CASE           WHEN @dummy <=> Score THEN @Rank := @Rank            ELSE @Rank := @Rank +1    END AS Rank,@dummy := Score as dummyFROM  (SELECT @Rank := 0,@dummy := NULL) r,     ScoresORDER BY Score DESC) AS C

或者:

# Write your MySQL query statement belowSELECT Scores.Score, COUNT(Ranking.Score) AS RANK  FROM Scores     , (       SELECT DISTINCT Score         FROM Scores       ) Ranking WHERE Scores.Score <= Ranking.Score GROUP BY Scores.Id, Scores.Score ORDER BY Scores.Score DESC;

  

  

 

 

转载于:https://www.cnblogs.com/carsonzhu/p/4655573.html

你可能感兴趣的文章
分享一套精美的现代 UI PSD 工具包【免费下载】
查看>>
彻底抛弃PeopleEditor,SharePoint中利用Jquery Chosen创建新的人员选择器
查看>>
用例图之我见
查看>>
jquery在调试时出现缺少对象的错误
查看>>
腾讯2012.9.23校园招聘笔试题
查看>>
TextView显示html文件中的图片
查看>>
xml xpath dta笔记
查看>>
[学习笔记]可编程管线(流水线),可编程着色语言
查看>>
hdu 4411(最小费用流)
查看>>
字符串匹配算法之KMP&Boyer-Moore
查看>>
[Python] heapq简介
查看>>
[转]SQL SERVER 函数组合实现oracle的LPAD函数功能
查看>>
SQL 必知必会·笔记<17>使用存储过程
查看>>
【Android】输入设备配置文件(.idc文件)
查看>>
元数据标签Embed
查看>>
1326: The contest(并查集+分组背包)
查看>>
编码规范(重要)
查看>>
drop有default constraint的column
查看>>
C# 异常类型
查看>>
C语言realloc,malloc,calloc的区别【转载】
查看>>