You have a table like so:
id dollars dollars_rank points points_rank
1 20 1 35 1
2 18 2 30 3
3 10 3 33 2
I want a query that updates the table's rank columns (dollars_rank
and points_rank
) to set the rank for the given ID, which is just the row's index for that ID sorted by the relevant column in a descending order. How best to do this in PostgreSQL?
@OMG_Ponies already pointed it out: The window function
dense_rank()
is what you need - or mayberank()
. TheUPDATE
could look like this:Test case:
UPDATE statement:
You need PostgreSQL 8.4 or later for window functions.