X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 9773D5E46D2 for ; Wed, 25 Aug 2004 14:47:42 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 72028-07 for ; Wed, 25 Aug 2004 17:47:33 +0000 (GMT) Received: from davinci.ethosmedia.com (server226.ethosmedia.com [209.128.84.226]) by svr1.postgresql.org (Postfix) with ESMTP id 0F1A15E3631 for ; Wed, 25 Aug 2004 14:47:33 -0300 (ADT) Received: from [63.195.55.98] (HELO spooky) by davinci.ethosmedia.com (CommuniGate Pro SMTP 4.1.8) with ESMTP id 6173060; Wed, 25 Aug 2004 10:48:51 -0700 Content-Type: text/plain; charset="iso-8859-1" From: Josh Berkus Organization: Aglio Database Solutions To: Andrew Perrin , pgsql-sql@postgresql.org Subject: Re: Complicated "group by" question Date: Wed, 25 Aug 2004 10:47:18 -0700 User-Agent: KMail/1.4.3 References: In-Reply-To: MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Message-Id: <200408251047.18645.josh@agliodbs.com> X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200408/265 X-Sequence-Number: 18762 Andrew, > I have a table of people ("reviewers"), a table of review assignments > ("assign"), and a table of review acceptances ("accept"). I would like to > be able to write a query to return the latest (e.g., max(assign_date)) > assignment for each reviewer, plus the acc_id field from "accept". I > think I should be able to do this with a GROUP BY clause, but am having no > luck. Some vagueness: you didn't say whether you wanted to see two assignments if they have the same, latest date. Nor did you specify whether you wanted to see assignments that had not been accepted (the below assumes yes to both) Hmmm ... one way, SQL-standard: SELECT reviewer.name, assign_date, acc_id FROM reviewers JOIN assign ON reviewer.id = assign.reviewer_id LEFT OUTER JOIN accept ON assign.id = accept.assign_id WHERE assign_date IN (SELECT max(ass2.assign_date) FROM assign ass2 WHERE ass2.reviewer_id = reviewers.id) or for a bit faster execution on PG you cann replace that WHERE clause with: WHERE assign_date IN (SELECT ass2.assign_date FROM assign ass2 WHERE ass2.reviewer_id = reviewers.id ORDER BY ass2.assign_date DESC LIMIT 1) -- Josh Berkus Aglio Database Solutions San Francisco