In this post, I will show you SQL query for calculateing dense rank for MySQL . You know Oracle and SQL Server have the function called DENSE_RANK, which is for returning rank of the value. Unfortunately MySQL doesn't have the built-in function. We can calculate dense rank by nested select for same table with count function. However this strategy is toooo slow because calculating rank by counting number of rows above the target row for every rows. Anyway here is the query for calculating dense rank for 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 The result should be something like this. id dns_rnk rnk score 1 1 1 100 4 2
IT関連の技術やプログラミングを中心に記事を書いています。ハードウェアも好きなので、日々のちょっとしたお役立ち情報も投稿しています。