Search code examples
sqlsql-serverranking

SQL ranking and ties


I'd like to rank some data

If I used a rank function with ties, the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.

example :

Value | Ranking 
1       1  
1       1 
1       1
1       1 
1       1  
2       6  

EDIT : I'd like to know if it's possible have these two versions :

Value | Ranking 
1       5    
1       5 
1       5  
1       5  
1       5   
2       6  

Value | Ranking 
1       3  
1       3 
1       3  
1       3 
1       3 
2       6  

I replace 1 by 3 because 3 is the median value of 1-2-3-4-5 (5 ties values)


Solution

  • SELECT Value, 
    count(*) over (partition by value)/2 + rank() over(order by value) as Ranking1, 
    count(*) over (partition by value) + rank() over(order by value) -1 as Ranking2 
    FROM table