標籤:report 4.0 table 函數 between 操作 連結 esc rds
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 |+-------+------+
解法:
1. With Variables(使用者定義變數): 700 ms
First one uses two variables, one for the current rank and one for the previous score.
SELECT Score, @rank := @rank + (@prev <> (@prev := Score)) RankFROM Scores, (SELECT @rank := 0, @prev := -1) initORDER BY Score desc
這種方法主要的思想就是基於變數。關鍵點是 選擇排名和上一個分數 兩個變數, 變數的初始化,判斷相同的分數的排名。mysql不像SQL有4個排名的函數可以調用,因此要自己來寫排名的功能。
類似的實現:
SELECT Score, Rank FROM( SELECT Score, @curRank := @curRank + IF(@prevScore = Score, 0, 1) AS Rank, @prevScore := Score FROM Scores s, (SELECT @curRank := 0) r, (SELECT @prevScore := NULL) p ORDER BY Score DESC) t;
2. Always Count: 1322 ms
This one counts, for each score, the number of distinct greater or equal scores.
SELECT Score, (SELECT count(distinct Score) FROM Scores WHERE Score >= s.Score) RankFROM Scores sORDER BY Score desc
沒太看懂這種演算法的思想。
補充知識:Mysql 使用者自訂變數詳解
你可以利用SQL語句將值儲存在使用者自訂變數中,然後再利用另一條SQL語句來查詢使用者自訂變數。這樣以來,可以再不同的SQL間傳遞值。
使用者自訂變數的聲明方法形如:@var_name,其中變數名稱由字母、數字、“.”、“_”和“$”組成。當然,在以字串或者標識符引用時也可以包含其他字元(例如:@’my-var’,@”my-var”,或者@`my-var`)。
使用者自訂變數是會話層級的變數。其變數的範圍僅限於聲明其的用戶端連結。當這個用戶端斷開時,其所有的會話變數將會被釋放。使用者自訂變數是不區分大小寫。
使用SET語句來聲明使用者自訂變數:
1 SET @var_name = expr[, @var_name = expr] ...
在使用SET設定變數時,可以使用“=”或者“:=”操作符進行賦值。當然,除了SET語句還有其他賦值的方式。比如下面這個例子,但是賦值操作符只能使用“:=”。因為“=”操作符將會被認為是比較操作符。
mysql> SET @t1=1, @t2=2, @t3:=4;mysql> SELECT @t1, @t2, @t3, @t4 := @[email protected][email protected];
[LeetCode] Rank Scores -- 資料庫知識(mysql)