搜索並嘗試了很多示例後,我無法弄清楚這一點。 希望你能幫助我。組內3種方式的更新排名
這是我的表測試:
+-------+-----------+----------+---------+---------+-------+
|Id | Class | Score | Rank1 | Rank2 | Rank3 |
+-------+-----------+----------+---------+---------+-------+
|1 | 1 | 9 | 0 | 0 | 0 |
|2 | 1 | 9 | 0 | 0 | 0 |
|3 | 1 | 8 | 0 | 0 | 0 |
|4 | 1 | 7 | 0 | 0 | 0 |
|5 | 2 | 9 | 0 | 0 | 0 |
|6 | 2 | 8 | 0 | 0 | 0 |
|7 | 2 | 8 | 0 | 0 | 0 |
|8 | 2 | 7 | 0 | 0 | 0 |
|9 | 2 | 6 | 0 | 0 | 0 |
+-------+-----------+----------+---------+---------+-------+
我想是更新我的表測試用3種排名:
- = 1級=每類具有連續排名在積分排名(沒有雙倍)
- =排名2 =連續排名的每級連續排名(雙)
- =排名3 = BLE)
E.g:
+-------+-----------+----------+---------+---------+-------+
|Id | Class | Score | Rank1 | Rank2 | Rank3 |
+-------+-----------+----------+---------+---------+-------+
|1 | 1 | 9 | 1 | 1 | 1 |
|2 | 1 | 9 | 2 | 1 | 1 |
|3 | 1 | 8 | 3 | 2 | 3 |
|4 | 1 | 7 | 4 | 3 | 4 |
|5 | 2 | 9 | 1 | 1 | 1 |
|6 | 2 | 8 | 2 | 2 | 2 |
|7 | 2 | 8 | 3 | 2 | 2 |
|8 | 2 | 7 | 4 | 3 | 4 |
|9 | 2 | 6 | 5 | 4 | 5 |
+-------+-----------+----------+---------+---------+-------+
注意:它必須是一個適用UPDATE語句中。
對於1,我發現(但無法弄清楚如何使一個UPDATE):
SET @prev := null;
SET @cnt := 0;
SELECT IF(@prev <> Class, @cnt := 1, @cnt := @cnt + 1) AS Rank, @prev := Class
FROM Test
ORDER BY Class;
對於3.我已經發現(但無法弄清楚如何使它一個UPDATE):
SELECT a.Id,
a.Score,
a.Class,
count(b.Score)+1 as Rank
FROM Test a left join Test b
on a.Score>b.Score and a.Class=b.Class
GROUP BY a.Id,
a.Score,
a.Class;
與十進制值基於分數時,我已經添加了結果。奇怪的排名出現:
SET @prev_class = 0,@class = 0,@prev_score = 0,@score = 0,@rank3 = 0,@count=0;
UPDATE 1i SET
Score_pq_raw_rank = (@prev_class := IFNULL(@class,0)),
Score_pq_raw_rank = (@class := Profile_id),
Score_pq_raw_rank = (@prev_score := IFNULL(@score,-1)),
Score_pq_raw_rank = (@score := Score_pq_raw),
Score_pq_raw_rank = (
CASE WHEN @prev_class != @class THEN @rank3 := 1
WHEN @prev_class = @class AND @prev_score = @score THEN @rank3
WHEN @prev_class = @class AND @prev_score != @score THEN @rank3:[email protected][email protected]
END),
Score_pq_raw_rank = (CASE WHEN @prev_class != @class THEN @count := 0
WHEN @prev_class = @class AND @prev_score = @score THEN @count := @count + 1
WHEN @prev_class = @class AND @prev_score != @score THEN @count := 0
END),
Score_pq_raw_rank = @rank3
ORDER BY Profile_id ASC, Score_pq_raw DESC, Rowresult_id ASC;
+--------------+--------------+------------+-------------------+
| Rowresult_id | Score_pq_raw | Profile_id | Score_pq_raw_rank |
+--------------+--------------+------------+-------------------+
| 1 | 3.69054000 | 1 | 1 |
| 2 | 0.10568000 | 1 | 2 |
| 3 | -2.08058000 | 1 | 3 |
| 4 | -2.07316000 | 1 | 3 |
| 5 | -2.39066000 | 1 | 3 |
| 6 | -10.23852000 | 2 | 3 |
| 7 | -8.77718000 | 2 | 2 |
| 8 | -7.38480000 | 2 | 1 |
| 9 | -13.49128000 | 2 | 4 |
| 10 | -19.36774000 | 2 | 5 |
+--------------+--------------+------------+-------------------+
你嘗試過什麼SQL語句rank3? – BLE
通常不會存儲派生數據 – Strawberry
我已更新我的問題 – Dev