mysql儲存函式查詢排名 MySQL排名函式

2021-10-18 03:18:41 字數 1642 閱讀 7358

應用場景:

編寫乙個 sql 查詢來實現分數排名。

如果兩個分數相同,則兩個分數排名(rank)相同。請注意,平分後的下乙個名次應該是下乙個連續的整數值。換句話說,名次之間不應該有「間隔」。

| id | score |

| 1 | 3.50 |

| 2 | 3.65 |

| 3 | 4.00 |

| 4 | 3.85 |

| 5 | 4.00 |

| 6 | 3.65 |

例如,根據上述給定的 scores 表,你的查詢應該返回(按分數從高到低排列):

| score | rank |

| 4.00 | 1 |

| 4.00 | 1 |

| 3.85 | 2 |

| 3.65 | 3 |

| 3.65 | 3 |

| 3.50 | 4 |

如上題,可以通過新版本mysql(8.0+)提供的dense_rank()排名函式實現。

select score, dense_rank() over(order by score desc) as `rank` from scores;

關於排名函式:

row_number:連續排名,即使相同的值,依舊按照連續數字進行排名。

這樣講可能有點抽象,我們看下實際使用的效果。

有一張學生分數表,資料如下:

mysql> select * from students;

| id | name | score |

| 1 | curry | 100 |

| 2 | klay | 99 |

| 3 | kd | 100 |

| 4 | green | 90 |

| 5 | james | 99 |

| 6 | ad | 96 |

根據三種不同的方法排序,sql如下:

select id, name, rank() over(order by score desc) as r,

dense_rank() over(order by score desc) as dense_r,

row_number() over(order by score desc) as row_r

from students;

結果:mysql> select id, name, rank() over(order by score desc) as r,

-> dense_rank() over(order by score desc) as dense_r,

-> row_number() over(order by score desc) as row_r

-> from students;

| id | name | r | dense_r | row_r |

| 1 | curry | 1 | 1 | 1 |

| 3 | kd | 1 | 1 | 2 |

| 2 | klay | 3 | 2 | 3 |

| 5 | james | 3 | 2 | 4 |

| 6 | ad | 5 | 3 | 5 |

| 4 | green | 6 | 4 | 6 |

6 rows in set (0.00 sec)

怎麼樣,是不是一目了然呢?

mysql 查詢字段排名 mysql 查詢排名

sql語句查詢排名 思路 有點類似迴圈裡面的自增一樣,設定乙個變數並賦予初始值,迴圈一次自增加1,從而實現排序 mysql裡則是需要先將資料查詢出來並先行按照需要排序的字段做好降序desc,或則公升序asc,設定好排序的變數 初始值為0 a 將已經排序好的資料從第一條依次取出來,取一條就自增加一,實...

mysql 當前排名查詢 mysql排名查詢

排名函式的型別 row number函式 不考慮並列名次的情況。比如前3名是並列的名次,row number函式排名之後是正常的1,2,3,4。通用的mysql排名解法 由於mysql8.0才有視窗函式解決排名問題,之前的版本需要自行實現排名函式,我寫了一些通用的sql套用以上的排名場景,以下sql...

mysql 排名函式 MySQL排名函式實現

資料庫準備 建立乙個分數表s score create table s score id int not null auto increment,score int not null default 0,name varchar 20 character set utf8mb4 null,prima...