简体   繁体   中英

SQL return the rank of an item

how to make a query that gets the rank of an item? (for azure database)

for example:

table name: studentScore

    studentName Scrore 
    student1      80
    student2      70
    student3      90
    student4      60

want to get the rank of student1, which is 2.

what I tried:

SELECT ROW_NUMBER() OVER(ORDER BY [Scrore])AS Rank 
FROM studentScore where [name] = 'student1'

return

Rank
  1

I want

Rank
 2

You can use rank() or dense_rank() functions:

declare
    @t table (studentName varchar (100), Score int)

  insert into @t
  values 
    ('student1', 80),
    ('student2', 70),
    ('student3', 90),
    ('student4', 60)

    select rank() over (order by Score desc) rnk, * from @t

    select dense_rank() over (order by Score desc) rnk, * from @t

OUTPUT

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM