Re: a SQL query question

From: Klint Gore <kgore4(at)une(dot)edu(dot)au>
To: Rajarshi Guha <rguha(at)indiana(dot)edu>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: a SQL query question
Date: 2008-07-29 03:05:09
Message-ID: 488E88E5.1010302@une.edu.au
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Rajarshi Guha wrote:
> What I'm trying to do is to select those rows where pid is not null,
> grouped by pid.
>
> From within each group I'd like to select the row that has the
> maximum value of nmol.
>
Distinct on should do the job for you.
select distinct on (pid) aid, pid, nmol
from atable
where pid is not null
order by pid, nmol desc

If you want the rows tie for max nmol within a pid then you can go to
select aid,pid,nmol
from atable
where (pid,nmol) in (select pid, max(nmol) from atable where pid is
not null group by pid)

klint.

--
Klint Gore
Database Manager
Sheep CRC
A.G.B.U.
University of New England
Armidale NSW 2350

Ph: 02 6773 3789
Fax: 02 6773 3266
EMail: kgore4(at)une(dot)edu(dot)au

In response to

Browse pgsql-general by date

  From Date Subject
Next Message brian 2008-07-29 03:23:23 Re: a SQL query question
Previous Message Tom Lane 2008-07-29 03:00:41 Re: why can't I load pgxml.sql