Gabriel Lam
Gabriel Lam

Reputation: 103

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

Upvotes: 0

Views: 45

Answers (1)

dzhukov
dzhukov

Reputation: 383

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

OUTPUT

Upvotes: 2

Related Questions