pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Richard Broersma Jr <rabroersma@yahoo.com>
To: wen tseng <went@hteamericas.com>
To: pgsql-sql@postgresql.org
Subject: Re: How to find out top 3 records in each location
Date: Mon, 20 Nov 2006 09:49:19 -0800 (PST)
Message-ID: <452822.24102.qm@web31801.mail.mud.yahoo.com> (raw)
In-Reply-To: <00e001c70cc6$926292a0$6f0aa8c0@miswen>

> On PostgreSQL, I have a table like this:
> 
> Item     Location    Sales
>  A            X             10
>  B            X              6
>  C            Y              3
>  D            Y              8
>  E            Y              15
>  F            Y             11
> 
> I'd like to find out top 3 items in each location and put those 3 items as colum values like
> this:
> 
> Location    Top1   Top2   Top3
>   X              A        B
>   Y             E         F        D
> 
> Since PostgreSQL doesn't support TOP, how can I do to get this result?
> Any solution will be appreciated.


Here is what I came up with.  However, I am sure there maybe a better answer.

SELECT 
	A1.location,
	( select sales
	  from sales
	  where location = A1.location
	  order by sales desc 
	  limit 1
	) as TOP1,
	( select sales
	  from sales
	  where location = A1.location
	  order by sales desc 
	  limit 1 offset 1
	) as Top2,
	( select sales
	  from sales
	  where location = A1.location
	  order by sales desc
	  limit 1 offset 2
	) as Top3


FROM
	( SELECT location
	  from sales
	  group by location
	) AS A1
;


Regards,

Richard Broersma Jr.



view thread (4+ messages)  latest in thread

Message-ID: <452822.24102.qm@web31801.mail.mud.yahoo.com>
Permalink:  ../452822.24102.qm@web31801.mail.mud.yahoo.com/
Also on:    postgresql.org/message-id/452822.24102.qm@web31801.mail.mud.yahoo.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: rabroersma@yahoo.com, went@hteamericas.com
  Subject: Re: How to find out top 3 records in each location
  In-Reply-To: <452822.24102.qm@web31801.mail.mud.yahoo.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox