Re: Selecting All Columns Associated With Maximum Value of One Column

From: David Johnston <polobo(at)yahoo(dot)com>
To: Rich Shepard <rshepard(at)appl-ecosys(dot)com>
Cc: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Selecting All Columns Associated With Maximum Value of One Column
Date: 2011-10-05 23:58:34
Message-ID: 8E8C44B9-20A3-4953-B80E-FA3F79816341@yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Oct 5, 2011, at 19:34, Rich Shepard <rshepard(at)appl-ecosys(dot)com> wrote:

> A table (chemistry) has columns named site_id, sample_date, param, quant,
> and str_name (among other columns). I want to find the site_id, sample_date,
> and quant for a specific str_name and param. I cannot get the proper syntax
> in the SELECT statement.
>
> My attempts are variations of,
>
> SELECT max(quant), param, site_id, sample_date, str_name from chemistry
> WHERE param = 'TDS' AND str_name = 'BurrowCrk';
>
> which prompts postgres to tell me,
>
> ERROR: column "chemistry.param" must appear in the GROUP BY clause or be
> used in an aggregate function
>
> I suspect that retrieving these data requires nested SELECT statements,
> and I'd appreciate learning how to retrive such data.
>
> Rich

"Max" is an aggregate function and thus requires one of:
1) GROUP BY
2) "Window" - max(quant) OVER (PARTITION BY ...)

To be present in the query.

A correlated sub-select would work but you would still need to use group by and you would not gain anything in this particular scenario.

They each have their own usage scenarios and your description is not sufficient to determine which one you need; but likely adding an appropriate GROUP BY clause will get you what you want.

Also, while the warning only specifies the param field all the other field will give you the same error if you use the GROUP BY claus. The Window syntax affects just the aggregate function and so only that single "field" would need to be modified BUT the window clause results in all records remaining in the final query whereas the GROUP BY clause effectively removes duplicates.

David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Amit Dor-Shifer 2011-10-06 00:07:59 plpgsql: type of array cells
Previous Message Rich Shepard 2011-10-05 23:34:49 Selecting All Columns Associated With Maximum Value of One Column