2

say I wish to create a table like following:

user   score   rank
a      100     2   
b      200     1
c      50      3
d      50      3

How exactly do I create a rank column in which it updates with the new entry of record with score?

Bango
  • 288
  • 1
  • 13

1 Answers1

1

For a small table, the easiest way is a correlated subquery:

select t.*,
       (select 1 + count(*)
        from t t2
        where t2.score > t.score
       ) as rank
from t 
order by score desc;

Note: this implements "rank" as per the rank() window function available in most databases.

Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709