Received: from davinci.ethosmedia.com (davinci.ethosmedia.com [209.10.40.250]) by postgresql.org (8.11.3/8.11.4) with ESMTP id f78K4l617901 for ; Wed, 8 Aug 2001 16:04:47 -0400 (EDT) (envelope-from josh@agliodbs.com) Received: from [209.10.40.250] (account ) by davinci.ethosmedia.com (CommuniGate Pro WebUser 3.4.1) with HTTP id 99001; Wed, 08 Aug 2001 13:04:39 -0700 From: "Josh Berkus" Subject: Re: Problem with aggregate functions and GROUP BY To: "Alex Page" Cc: pgsql-sql@postgresql.org X-Mailer: CommuniGate Pro Web Mailer v.3.4.1 Date: Wed, 08 Aug 2001 13:04:39 -0700 Message-ID: In-Reply-To: <02ac01c12025$78644300$7fc472c1@solidstatelogic.com> MIME-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 8bit X-Archive-Number: 200108/136 X-Sequence-Number: 4357 Alex, > which is the highest value of 'sortby' for each value of 'fk'. > > I would think that the SQL to achieve this is: > > SELECT * FROM test GROUP BY fk HAVING sortby = MAX(sortby); You need a subselect for this: SELECT test.* FROM test, (SELECT max(sortby) as maxsort, fk FROM test GROUP BY fk) maxtest WHERE test.fk = maxtest.fk AND test.sortby = maxtest.maxsort; There's also a pgsql extension called SELECT DISTINCT ON, but it's not SQL 92 standard so I don't reccomend it. -Josh ______AGLIO DATABASE SOLUTIONS___________________________ Josh Berkus Complete information technology josh@agliodbs.com and data management solutions (415) 565-7293 for law firms, small businesses fax 621-2533 and non-profit organizations. San Francisco