select top N entries from several groups - Mailing list pgsql-novice

From David Orme
Subject select top N entries from several groups
Date
Msg-id dcd576342084fcc7eca3be281beccf33@ic.ac.uk
Whole thread Raw
Responses Re: select top N entries from several groups  (Sean Davis <sdavis2@mail.nih.gov>)
List 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


pgsql-novice by date:

Previous
From: Tom Lane
Date:
Subject: Re: Postgres startup
Next
From: Sean Davis
Date:
Subject: Re: select top N entries from several groups