I have a table that looks something like this:
CREATE TABLE student_results(id integer, name varchar(32), score float);
Lets make the following two assumptions:
- assume that the score goes from 0 to a maximum of 100.
- assume that I want to grade students in ‘step sizes’ of 10
so I want to apply the following grading:
Score Grade Awarded
0-10 GRADE9
10-20 GRADE8
20-30 GRADE7
30-40 GRADE6
40-50 GRADE5
50-60 GRADE4
60-70 GRADE3
70-80 GRADE2
80-90 GRADE1
99-100 GENIUS
I would like to write an SQL query that takes in the following input arguments:
lowest score: 0 in this example
highest score: 100 in this example
'step' size: 10 in this example
As ever, if possible, I would like to write such a query using ANSI SQL. If I have to choose a database, then in order of DECREASING preference, it would have to be:
- PostgreSQL
- MySQL
Could someone please explain how I may be able to write an SQL query that does this kind of grading, using the above table as an example?
[Edit]
Sample input data
1, 'homer', 10.5
2. 'santas little helper', 15.2
3, 'bart', 20.5
4, 'marge', 40.5
5. 'lisa', 100
I will have an SQL function grade_rank() – that ranks the student:
The arguments for function grade_rank() are :
1st argument: LOWEST possible score value
2nd argument: HIGHEST possible score value
3rd argument: step size, which determines the levels/divisions between the ranks
select id, name, grade_rank(0,100, 10) grade from student_scores;
the output (based on the input above) should be:
1, homer, GRADE9
2. santas liitle helper GRADE9
3, bart, GRADE8
4, marge, GRADE6
5. lisa, GENIUS
In this way you can do it more general but the grades will be in reverse order, starting from 1 up to N, ie
For example using the values
step 10
score 43
This algorithm
SELECT (((score-1)-((score-1) % step))/step)+1will return 5
You don’t have to know the maximum score. If the max score is 100 no one will be able to perform higher than 100, you just have to decide the size of the steps. For example if you want a step size of 25. Knowing that the maximum score is 100 there will be 4 grade levels. So by setting step level to 25 instead of 10 the result will be 2, ie grade 2.
Perhaps not right on spot what you expected but maybe generic enough to be useful. Here is how the function would look like in SQL.
Now calling this function
returns 5.
And this the plpgsql equivalent: