Re: select top N entries from several groups

From: Sean Davis <sdavis2(at)mail(dot)nih(dot)gov>
To: David Orme <d(dot)orme(at)imperial(dot)ac(dot)uk>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: select top N entries from several groups
Date: 2005-04-12 12:21:40
Message-ID: 196de90c16ccbc5a3999000f6110c334@mail.nih.gov
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice


On Apr 12, 2005, at 7:21 AM, David Orme wrote:

> 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...

How about:

create table temp (
gp char,
val int
);

insert into temp values ('A',10);
insert into temp values ('A',8);
insert into temp values ('A',6);
insert into temp values ('A',4);
insert into temp values ('B',3);
insert into temp values ('B',2);
insert into temp values ('B',1);

select a.gp,a.val
from temp a
where a.val in (
select b.val
from temp b
where a.gp=b.gp
order by b.val desc
limit 2);

gp | val
----+-----
A | 10
A | 8
B | 3
B | 2
(4 rows)

I have found this link is useful for beginning to think about
subqueries:

http://www.postgresql.org/files/documentation/books/aw_pgsql/node81.html

Sean

In response to

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Reinhard Hnat 2005-04-12 13:53:38 Re: select top N entries from several groups
Previous Message David Orme 2005-04-12 11:21:29 select top N entries from several groups