X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id 952919DC86B for ; Sun, 12 Mar 2006 01:42:22 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 28877-09 for ; Sun, 12 Mar 2006 01:42:21 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey- Received: from tigger.fuhr.org (tigger.fuhr.org [63.214.45.158]) by postgresql.org (Postfix) with ESMTP id 393E89DC833 for ; Sun, 12 Mar 2006 01:42:17 -0400 (AST) Received: from winnie.fuhr.org (winnie.fuhr.org [10.1.0.1]) by tigger.fuhr.org (8.13.3/8.13.3) with ESMTP id k2C5gC6Q092774 (version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=OK); Sat, 11 Mar 2006 22:42:15 -0700 (MST) (envelope-from mfuhr@winnie.fuhr.org) Received: from winnie.fuhr.org (localhost [127.0.0.1]) by winnie.fuhr.org (8.13.4/8.13.4) with ESMTP id k2C5gCR6025538; Sat, 11 Mar 2006 22:42:12 -0700 (MST) (envelope-from mfuhr@winnie.fuhr.org) Received: (from mfuhr@localhost) by winnie.fuhr.org (8.13.4/8.13.4/Submit) id k2C5gC7R025537; Sat, 11 Mar 2006 22:42:12 -0700 (MST) (envelope-from mfuhr) Date: Sat, 11 Mar 2006 22:42:12 -0700 From: Michael Fuhr To: Weimao Ke Cc: pgsql-sql@postgresql.org Subject: Re: pgsql aggregate: conditional max Message-ID: <20060312054212.GA25423@winnie.fuhr.org> References: <4413AD1C.9050604@indiana.edu> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <4413AD1C.9050604@indiana.edu> X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.121 required=5 tests=[AWL=0.121] X-Spam-Score: 0.121 X-Spam-Level: X-Archive-Number: 200603/170 X-Sequence-Number: 24516 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