pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Michael Fuhr <mike@fuhr.org>
To: Weimao Ke <wke@indiana.edu>
Cc: pgsql-sql@postgresql.org
Subject: Re: pgsql aggregate: conditional max
Date: Sat, 11 Mar 2006 22:42:12 -0700
Message-ID: <20060312054212.GA25423@winnie.fuhr.org> (raw)
In-Reply-To: <4413AD1C.9050604@indiana.edu>
References: <4413AD1C.9050604@indiana.edu>

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



view thread (9+ messages)  latest in thread

Message-ID: <20060312054212.GA25423@winnie.fuhr.org>
Permalink:  ../20060312054212.GA25423@winnie.fuhr.org/
Also on:    postgresql.org/message-id/20060312054212.GA25423@winnie.fuhr.org

 · 

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: mike@fuhr.org, wke@indiana.edu
  Subject: Re: pgsql aggregate: conditional max
  In-Reply-To: <20060312054212.GA25423@winnie.fuhr.org>

* 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