I have a table like this:
Date StudentName Score 01.01.09 Alex 100 01.01.09 Tom 90 01.01.09 Sam 70 01.02.09 Alex 100 01.02.09 Tom 50 01.02.09 Sam 100
I need to rank the students in the result table by score within different dates, like this:
Date Student Rank 01.01.09 Alex 1 01.01.09 Tom 2 01.01.09 Sam 3 01.02.09 Alex 1 01.02.09 Sam 1 01.02.09 Tom 2
How can I do this in SQL?
Introduction to SQL RANK () RANK () in standard query language (SQL) is a window function that returns a temporary unique rank for each row starting with 1 within the partition of a resultant set based on the values of a specified column when the query runs. The rank of a row is its sequential number within the partition set.
Summary: in this tutorial, you will learn how to use SQL RANK () function to find the rank of each row in the result set. The RANK () function is a window function that assigns a rank to each row in the partition of a result set.
The ORDER BY clause sorted the rows in the result by salary. The RANK() function then is applied to each row in the result considering the order of employees by salary in descending order. Using SQL RANK() function over partition example. The following statement finds the employees who have the second highest salary in their departments:
Note that if you want to have consecutive ranks, you can use the DENSE_RANK () function. We will use the employees and departments table from the sample database for the demonstration. The following statement ranks employees by their salaries:
You want to use the rank
function in T-SQL:
select
date,
student,
rank() over (partition by date order by score desc) as rank
from
grades
order by
date, rank, student
The magic is in the over
clause. See, it splits up those rankings by date
, and then orders those subsets by score
. Brilliant, eh?
You should use ORDER BY
:
SELECT * FROM Students ORDER BY Date,Rank
That will order the data by date, then rank. You can add as many fields as you want, as long as they are comparable (you can't compare BLOBs or long text fields).
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With