Skip site navigation (1) Skip section navigation (2)

Re: SQL query question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: alloni(at)aposiopesis(dot)net
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: SQL query question
Date: 2005-08-15 00:31:02
Message-ID: 4991.1124065862@sss.pgh.pa.us (view raw or flat)
Thread:
Lists: pgsql-novice
"Alloni Kramer" <alloni(at)aposiopesis(dot)net> writes:
> Simplified version of problem:  We have a table.  We'll say it has four
> variables, a, b, c, and squelch, all ints.  I want to get all values of
> these variables for which:

> c is within a certain range of values (call it between 3 and 5).
> for any given value of a, c is maximum.
>  - and -
> for any given value of a for which c is maximal, b is maximum.  That is,
> if we have the values of

This isn't perfectly clear, but I think what you are after can be done
with

	select distinct on (a) * from mytab
	where c between 3 and 5
	order by a, c desc, b desc;

The "weather report" example in the SELECT reference page may be
helpful.

It's possible to do this without the nonstandard DISTINCT ON clause,
but it's a lot more tedious (and I forget just how at the moment ;-))

			regards, tom lane

In response to

pgsql-novice by date

Next:From: Steve PoeDate: 2005-08-15 09:36:45
Subject: Re: Uploading and loading
Previous:From: rbradleyDate: 2005-08-14 22:12:20
Subject: Intsall 8.03 on Redhat ES 3

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group