select a ranking

From: Janning Vygen <vygen(at)gmx(dot)de>
To: pgsql-general(at)postgresql(dot)org
Subject: select a ranking
Date: 2002-07-18 13:29:10
Message-ID: 200207181329.g6IDTCX22948@janning.planwerk6.local
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

i do some ordering on a table and need a ranking by points from a
table with names and points (see sample code at the end of the mail)

i would like to get a table with numbers in front of it
like
1. jim 13
2. bob 15
2. john 15
4. peter 20

i ve thought of it and made the conclusion the easiest way is with
sequences (see below: working code, tested). it works fine, but seems
to be very complicated because i do an ordering in the first place
anyway, so it would be easy to add ranking in the client application.

and sequences are not sql standard, aren't they?

so heres is my question:
is there an easier way to create a ranking?

kind regards,
janning

only code below this line
-----------------------
-- startup
CREATE TABLE person (name text, points int4);
INSERT INTO person VALUES ('jim', 10);
INSERT INTO person VALUES ('john', 13);
INSERT INTO person VALUES ('bob', 13);
INSERT INTO person VALUES ('carl', 15);
-- get ranking
CREATE SEQUENCE ranking;
CREATE TEMP TABLE rank1 AS
SELECT nextval('ranking') AS rank, *
FROM (
SELECT name, points
FROM person
ORDER BY points
) AS rank;

SELECT CASE WHEN COALESCE(r2.points, -1) = r1.points
THEN r2.rank
ELSE r1.rank
END AS ranking,
r1.name,
r1.points
FROM rank1 AS r1
LEFT JOIN rank1 AS r2
ON (r2.rank = r1.rank - 1);
-- garbage collection
DROP SEQUENCE ranking;
DROP TABLE rank1;
DROP TABLE person;

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2002-07-18 13:46:21 Re: OIDs (Or: another RTFM question?)
Previous Message Bruno Wolff III 2002-07-18 13:09:09 Re: SQL If-Then Logic in Query