Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ranking Students by Grade in SQL

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?

like image 303
iLemming Avatar asked Aug 11 '09 20:08

iLemming


People also ask

What is rank () 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.

How to find the rank of each row in result 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.

How to use rank () function over partition in SQL Server?

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:

How to have consecutive ranks of employees in a database?

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:


2 Answers

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?

like image 104
Eric Avatar answered Oct 05 '22 16:10

Eric


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.

like image 42
dguaraglia Avatar answered Oct 05 '22 16:10

dguaraglia