Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In this way you can do it more general but the grades will be in reverse order, starting from 1 up to N, ie</p> <ul> <li>0-10 Grade1 </li> <li>10-20 Grade2 </li> <li>20-30 Grade3 </li> <li>30-40 Grade4</li> <li>...</li> </ul> <p>For example using the values step 10 score 43</p> <p>This algorithm</p> <p><code>SELECT (((score-1)-((score-1) % step))/step)+1</code></p> <p>will return 5</p> <p>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. </p> <pre><code>SELECT (((43-1)-((43-1) % 25))/25)+1 </code></pre> <p>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.</p> <pre><code>CREATE OR REPLACE FUNCTION grade_rank(IN score integer, IN step integer, OUT rank integer) AS 'SELECT ((($1-1)-(($1-1) % $2))/$2)+1' LANGUAGE 'SQL'; </code></pre> <p>Now calling this function</p> <pre><code>select * from grade_rank(43,10) </code></pre> <p>returns 5.</p> <p>And this the plpgsql equivalent:</p> <pre><code>CREATE OR REPLACE FUNCTION grade_rank(IN score integer, IN step integer) RETURNS integer AS $BODY$ DECLARE rank integer; BEGIN SELECT (((score-1)-((score-1) % step))/step)+1 INTO rank; RETURN rank; END; $BODY$ LANGUAGE 'plpgsql'; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload