select top N entries from several groups

From: David Orme <d(dot)orme(at)imperial(dot)ac(dot)uk>
To: pgsql-novice(at)postgresql(dot)org
Subject: select top N entries from several groups
Date: 2005-04-12 11:21:29
Message-ID: dcd576342084fcc7eca3be281beccf33@ic.ac.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Hi,

Suppose I have a table (called temp) like this:

gp val
A 10
A 8
A 6
A 4
B 3
B 2
B 1
B 0

How can I get the largest two values for each group in a single pass? I
want to end up with:

gp val
A 10
A 8
B 3
B 2

I can do this a group at a time using...

SELECT gp, val FROM temp where gp = 'A' ORDER BY val DESC LIMIT 2;

... and then insert the results from each group into a final table. Can
I get it in one go?

Thanks,
David

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Sean Davis 2005-04-12 12:21:40 Re: select top N entries from several groups
Previous Message Tom Lane 2005-04-12 05:34:05 Re: Postgres startup