This query DOES NOT give expected result,
What i am trying to do :
I am trying to rank user based on two different column/field and value. And want to show highest ranking user on top.
I am creating dummy column in select query as RANK and using two CASE … AS RANK.
Is this good practice? Or any better way out?
PS : I really dont want to persist RANK so not storing them, as it will be dynamic from various fields (this is just and example with two fields)
SELECT *,
CASE EMPLOYEEOF
WHEN 'ASDF' THEN @RANK := @RANK+1
END AS RANK,
CASE VENDOROF
WHEN 'WXYZ' THEN @RANK := @RANK+1
END AS RANK
from USERMASTER, (SELECT @RANK := 0) r ORDER BY RANK DESC;
EDIT : DOES NOT GIVE! in line 1
If you want to select from a table (USERMASTER), generate a calculated rank and then sort by that given rank, here’s how you can do that effectively.
1) Determine your ranking criteria – Figure out what matters to your rank, whether it’s money spent, student grade, etc, knowing what your metrics are will help.
2) Write your logic – CASE statements are great when more than one condition is included. For example if you wanted to give a higher rank to a student with both a GPA above 3.0 and a grade in a class equal to an “A”, but you want to give a lower rank to lower GPA, you might say:
This will create a rank column based on student_grade and student_gpa logic, then sort the students based on this calculated rank in order of highest rank first.
3) Test your cases – Verify that your logic gave you the results your looking for by reviewing some sample data. For my example (since I’m unaware of your criteria:
My results from running the above (with group by on student_name):
My results lined up with my expected outcome (John’s rank is higher at 4 and also shows up on top of my list due to order by) and we are done!