[SQL Miner] - window function - rank

introduce:

rank() is a commonly used window function that assigns a rank to each row in the result set. This ranking is based on the specified sort order, and when identical values ​​are encountered, identical rankings are skipped.

usage:

The syntax of the rank() function is as follows:

rank() over ([partition by 列名1, 列名2, ... order by 列名 [asc|desc], ...])

In this syntax, partition by is optional, which means to partition the result set according to the specified column or expression. Each partition generates an independent ranking sequence, making the ranking unique within each partition.

order by is used to specify the sort order, which can be sorted according to one or more columns. The sorting method can be specified using asc (ascending, the default) or desc (descending).

Example:

Here is an example showing how to use the rank() function:
Assume we have a table named scores that contains the grade information of the students, such as student name (studentname) and grade (score). We want to generate a rank for each student in descending order of grades.

select 
studentname, score,
rank() over (order by score desc) as ranking
from scores;

In this example, we use the rank() function to create a column named ranking that contains the ranking sorted by score in descending order. Each row in the result set is assigned a rank, and students with the same score will share the same rank.

Note that the rank() function may skip ranking. For example, if two students' grades are tied for 1st place, the next grade will be skipped and they will go straight to 3rd place.

Guess you like

Origin blog.csdn.net/qq_40249337/article/details/131999570