25 Advanced SQL Queries - Sort Rows Based on Specific Sort Criteria

Many of the examples in this column will be based on the following employee table (employee). Only a few examples will be based on other tables; in these cases the tables will be illustrated along with the examples.

1. RANK function

The RANK() function is one of the window functions in SQL. Window functions look at a portion of data and compute results for that portion.

The RANK() function assigns each row a rank based on the columns provided. RANK() is included in the SELECT statement with the following syntax:

RANK() OVER (ORDER BY column ASC|DESC)

Basically, you can add another column to the result set. This column includes the rank of each record based on the order specified after the ORDER BY keyword. This requires specifying (1) the column to use to sort the rows, and (2) whether the order should be ascending or descending.

The first row has rank 1, and the following rows have higher ranks. If any row has the same value in the column used for sorting, their ranks are the same, and RANK will skip the specified number at this time, that is, if two rows have the same value in the sorted column, skip a number, If there are three, two numbers are skipped, and so on.

For example, if the fifth and sixth rows have the same value in the provided column, they both get rank 5. Then, the seventh line gets rank 7 (ie, rank 6 will be lost), eg:

Guess you like

Origin blog.csdn.net/wyxtx/article/details/131722008