Weydiinta SQL si loo go'aamiyo liiska darajaynta

Maanta waxaan la kulmay hawsha soo socota anigoo ka shaqeynaya mashruuc macaamil: Qaado miiska SQL "isticmaale" oo leh tiirarka "id" iyo "score" oo go'aan ka gaar qiimeynta dhammaan isticmaaleyaasha ku saleysan "dhibic" taas oo isticmaaleyaasha leh hel isla darajo isku dhibco ah. Hawshan waxaa lagu xallin karaa si macquul ah oo fudud iyadoo la adeegsanayo doorsoomayaal adeegsadeyaal lagu qeexay .


CREATE TABLE
    user(id INT, score INT);
INSERT INTO
    user(id, score)
VALUES
    (1, 10), (2, 40), (3, 55), (4, 10), (5, 5), (6, 20), (7, 30), (8, 70), (9, 30)

Adeegsiga laba doorsoome ayaa tan si fudud ku xalinaya

SET @score_prev = NULL;
SET @cur_rank = 0;
SELECT id, score, CASE
    WHEN @score_prev = score THEN @cur_rank
    WHEN @score_prev := score THEN @cur_rank := @cur_rank + 1
END AS rank
FROM user
ORDER BY score DESC

waxaadna heleysaa wax soo saarka aad rabto

+--------+-----------+----------+
|  *id*  |  *score*  |  *rank*  |
|    8   |      70   |      1   |
|    3   |      55   |      2   |
|    2   |      40   |      3   |
|    7   |      30   |      4   |
|    9   |      30   |      4   |
|    6   |      20   |      5   |
|    1   |      10   |      6   |
|    4   |      10   |      6   |
|    5   |       5   |      7   |
+--------+-----------+----------+
Dib u laabo