Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to rank in SQL

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to rank in SQL". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to rank in SQL.

Let's first create a test data table Scores

WITH t AS (SELECT 1 StuID,70 Score UNION ALL SELECT 2 85 UNION ALL SELECT 3 UNION ALL SELECT 4 80 UNION ALL SELECT 5 74) SELECT * INTO Scores FROM t; SELECT * FROM Scores

The results are as follows:

1. ROW_NUMBER ()

Definition: the function of the ROW_NUMBER () function is to sort the data queried by SELECT, each with a serial number, which can not be used for student performance ranking, but is generally used for paging queries, such as the first 10 queries for 10-100 students.

1.1 ranking of students' scores

Example

SELECT ROW_NUMBER () OVER (ORDER BY SCORE DESC) AS [RANK], * FROM Scores

(hint: you can swipe the code left and right)

The results are as follows:

Here RANK is the order in which each student is ranked, and DESC is reversed according to Score.

1.2 get the second place score information SELECT * FROM (SELECT ROW_NUMBER () OVER (ORDER BY SCORE DESC) AS [RANK], * FROM Scores) t WHERE t.RANK=2

Results:

The idea used here is that the idea of paging query is to nest a layer of SELECT in addition to the original sql.

WHERE t.RANK > = 1 AND t.RANK

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report