Skip to content
Advertisement

How to rank values in SQL for an existing and pre-arranged set

INPUT_FIELD1,INPUT_FIELD2
1,A
2,A
3,A
4,B
5,B
6,A
7,B
8,A
9,B
10,C
11,B
12,B
13,B
14,D

INPUT_FIELD1,INPUT_FIELD2,OUTPUT_FIELD3
1,A,1
2,A,1
3,A,1
4,B,2
5,B,2
6,A,3
7,B,4
8,A,5
9,B,6
10,C,7
11,B,8
12,B,8
13,B,8
14,D,9

I will need the implementation in SQL only and not PL-SQL or any other programming method.

Advertisement

Answer

This is a gaps-and-islands problem. In this case, lag() and a cumulative sum does what you want:

select t.*,
       sum(case when prev_col2 = col1 then 0 else 1 end) over (order by col1) as ranking
from (select t.*,
             lag(col2) over (order by col1) as prev_col2
      from t
     ) t
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement