Forum OpenACS Q&A: SQL question

Collapse
Posted by Ola Hansson on
I have a table with the columns player_id and rating and would like to query PostgreSQL in a way so that it returns "ranking" as well, like so:

player_idratingranking
12101
21122
31122
4253

(Players with identical rating should have the same ranking)

Anyone know how this can be achieved?
Collapse
2: Response to SQL question (response to 1)
Posted by Jonathan Ellis on
the easiest way would be to have whatever's looping through the rows PG returns compute the ranking as it goes.
Collapse
3: Response to SQL question (response to 1)
Posted by Paul Sharples on
I don't have a Postgresql query but the following works in Oracle (and I know it's irrelevant but I've done it now, so there).

SELECT p.player_id, p.rating, q.ranking
  FROM player_rating_tab p,
      (SELECT r.rating rating, rownum ranking
         FROM (SELECT DISTINCT rating
                 FROM acs_tab
                ORDER BY rating DESC) r
      ) q
 WHERE p.rating = q.rating
 ORDER BY q.ranking

SQL> /

 PLAYER_ID     RATING    RANKING
---------- ---------- ----------
         1        210          1
         2        112          2
         3        112          2
         4         25          3

SQL>
I shudder to think how the query plan would look for this.

You'll find plenty of better answers, I'm sure. Joe Celko must have answered this type of question hundreds of times so if you have access to his columns or books, that might be a good place to look.

If I had to do this for real, I'd use Jonathan's advice and do it in a procedure.

Collapse
4: Response to SQL question (response to 1)
Posted by Ola Hansson on
Thanks Jonathan and Paul!

"rownum" doesn't exist in PG 7.1.3, it seems, at least the query choked on that.

I am using "ad_table" (this is one GREAT proc) in 3.2.5 to display the results to make the columns sortable. Modifying ad_table should be easy and so I'll follow your recomendations. Thanks again.