Skip to content

Instantly share code, notes, and snippets.

@heluvaguy
Created October 7, 2013 15:09
Show Gist options
  • Save heluvaguy/6869549 to your computer and use it in GitHub Desktop.
Save heluvaguy/6869549 to your computer and use it in GitHub Desktop.
Implement Dense Rank In Mysql
SELECT id,
@rnk:=IF(@preval <=> score, @rnk, @row + 1) AS dns_rnk,
@row:= @row+1 AS rnk,
@preval:=score as score
FROM table
# be careful for NULL handling.
# if all the values of score column are null, then dns_rank will zero.
# please set proper initial value for @preval based on your data.
JOIN (SELECT @rnk := 0, @preval :=null, @row := 0) r
ORDER BY score DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment