Re: Select first ten of each category?

From: Michael Glaesemann <grzm(at)myrealbox(dot)com>
To: lists(at)benjamindsmith(dot)com
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Select first ten of each category?
Date: 2006-04-13 02:11:26
Message-ID: CF110118-98CF-47E0-BFA7-DE7BEF565411@myrealbox.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Apr 13, 2006, at 10:16 , Benjamin Smith wrote:

> I'm stumped on this one...
>
> I have a table defined thusly:
>
> create table items (
> id serial,
> category integer not null references category(id),
> name varchar not null,
> price real,
> unique(category, name));
>
> It has a LARGE number of entries. I'd like to grab the 10 most
> expensive items
> from each category in a single query. How can this be done?

You can use a correlated subquery, something like (untested):

select category, id, name, price
, (
select count(*)
from items i2
where i2.category = i.category
and i2.price > i.price
) + 1 as rank
from items i
order by category, rank desc;

Note that this query actually counts the number of items (in the
category) with prices greater than the given item's price.

And to limit it just to the top 10 items:

select category, id, name, price, rank
from (
select category, id, name, price
, (
select count(*)
from items i2
where i2.category = i.category
and i2.price > i.price
) + 1 as rank
from items i
)
where rank <= 10
order by category, rank desc;

Note that this may return more than 10 items per category in the case
of more than one item in a given category having the same price.

Hope this points you in the right direction.

Michael Glaesemann
grzm myrealbox com

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Brent Wood 2006-04-13 02:12:04 Re: Select first ten of each category?
Previous Message Yanni Chiu 2006-04-13 02:08:49 Re: Select first ten of each category?