Ordering Students According to Exam Scores Grouped by Their Classes Using DENSE_RANK() T-SQL Functions
Today, I was requested to solve a problem in a t-sql query which was assumed to point some software according to their usage capacities such as number of records, used disk space, left disk size, etc. on different servers.
And each criteria has diffent weight when compared to other criterias.
After each software instance installed on a server is calculated to sum up the resultant overall score I was asked to get the best ones in each server.
I was able to solve the problem by using one of the new T-SQL window functions in
SQL Server 2005, ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)
ROW_NUMBER() is a powerful function and if it is used with PARTITION BY it can solve numbering items within groups divided by column values for example.
Here is a sample using multiple DENSE_RANK() t-sql window functions within the same sql select query.
The above script will return the students and their exam results and the sort order of each exams result compared among other results in his/her class. Each exam has different weight (1, 2, 3 in this example). And the student with least exam score gets 1 * (weight of the exam), and the later student gets 2 * (weight of the exam) points.
If we want to get the best students in each class, then we can use the below query.
The reason why I preferred DENSE_RANK() to ROW_NUMBER() is there are some cases where some of the grouped students might have the same scores. In this case if ROW_NUMBER() is used then one student will be on top of the others although they have the same scores. DENSE_RANK() assigns the same order number to the group of students whose scores are identical.