Re: pgsql aggregate: conditional max - Mailing list pgsql-sql

From Michael Fuhr
Subject Re: pgsql aggregate: conditional max
Date
Msg-id 20060312054212.GA25423@winnie.fuhr.org
Whole thread Raw
In response to pgsql aggregate: conditional max  (Weimao Ke <wke@indiana.edu>)
Responses Re: pgsql aggregate: conditional max
List pgsql-sql
On Sun, Mar 12, 2006 at 12:09:48AM -0500, Weimao Ke wrote:
> I want to group by "aid" and choose the category (i.e., "cat") with the 
> largest "weight":
> 
> aid   |   max_weighted_cat
> ----+---------------------
> a1   |   Other
> a2   |   Drama
> a3   |   Adult

PostgreSQL has a non-standard DISTINCT ON clause that would work.
See the weather_reports example in the documentation for SELECT:

http://www.postgresql.org/docs/8.1/interactive/sql-select.html

Try this query against your example data:

SELECT DISTINCT ON (aid) aid, cat
FROM tablename
ORDER BY aid, weight DESC, cat;

If multiple rows for a given aid match that aid's max weight then
the above query will return the first matching row according to the
given sort order.

Some people object to DISTINCT ON because it's non-deterministic if
you don't order by enough columns.  Here's something more standard;
it'll return all rows that match a given aid's max weight:

SELECT aid, cat
FROM tablename AS t
JOIN (SELECT aid, max(weight) AS weight     FROM tablename     GROUP BY aid) AS s USING (aid, weight);

-- 
Michael Fuhr


pgsql-sql by date:

Previous
From: Jeffrey Melloy
Date:
Subject: Re: pgsql aggregate: conditional max
Next
From: Michael Fuhr
Date:
Subject: Re: pgsql aggregate: conditional max