Re: Selecting top N percent of records.

From: Darren Duncan <darren(at)darrenduncan(dot)net>
To: Tim Uckun <timuckun(at)gmail(dot)com>, pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Selecting top N percent of records.
Date: 2010-10-17 23:53:43
Message-ID: 4CBB8C87.8020409@darrenduncan.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Tim Uckun wrote:
> Is there a way to select the top 10% of the values from a column?
>
> For example the top 10% best selling items where number of sales is a column.

The top 10% would be a variable number of records. Is that what you want, or
would you rather, say, just see the top N items?

The latter is easy, just something like this:

SELECT * FROM mytbl ORDER BY num_sales DESC LIMIT $1

... where $1 is the number of records you want.

To actually get 10% of the records, you can replace the $1 with a subquery,
something like this probably:

SELECT * FROM mytbl ORDER BY num_sales DESC
LIMIT (SELECT (count(*) / 10) AS selnum FROM mytbl)

There are probably other ways to do it also.

Maybe you want all items whose sales are in the top 90 percentile or something,
or maybe you want what generated the most profit, etc.

-- Darren Duncan

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Kynn Jones 2010-10-17 23:54:25 Re: Fastest way to check database's existence
Previous Message Tim Uckun 2010-10-17 23:33:54 Selecting top N percent of records.