Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use RANK function in SQL

Shulou Source: shulou.com Published: 2022-06-01 02:56:18 09月10日 Update

This article is about how to use the RANK function in SQL. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

RANK

The rank function returns the ranking of each row in the partition of the result set, which is the number of rankings before the relevant rows plus one. To put it simply, the rank function is to rank the queried records. Unlike the row_number function, the rank function takes into account the situation of the same sort field value in the over clause. If you use the rank function to generate the sequence number, the order number with the same sort field value in the over clause is the same, and the sequence number with the same field value will skip the next ranking number, that is, the number of rankings before the relevant lines. It can be understood to generate sequence numbers based on the current number of records, subsequent records, and so on. Maybe what I describe is pale and difficult to understand. Let's go straight to the code. The rank function is used in exactly the same way as the row_number function.

Select RANK () OVER (order by [UserId]) as rank,* from [Order]

The query results are shown in the following figure:

As can be seen from the above figure, when the rank function is ranked, the sequence number of the same group is the same, while the following is based on the current number of records, and so on, the first and second records in the chart have the same user Id, so their sequence number is the same, and the sequence number of the third record is 3.

Thank you for reading! This is the end of the article on "how to use the RANK function in SQL". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Tags: Function serial number same field content clause more article result add one sort query generate different not bad laborious practical and so on above that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux NVidia Xiaomi Shulou Tech Info MySQL