X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id 27C14D1B860 for ; Thu, 19 Feb 2004 23:52:28 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 71268-02 for ; Thu, 19 Feb 2004 19:52:28 -0400 (AST) Received: from megazone.bigpanda.com (megazone.bigpanda.com [64.147.171.210]) by svr1.postgresql.org (Postfix) with ESMTP id 0DC27D1B4C5 for ; Thu, 19 Feb 2004 19:52:25 -0400 (AST) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id 44D2D35852; Thu, 19 Feb 2004 15:52:27 -0800 (PST) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id 435DF3584F; Thu, 19 Feb 2004 15:52:27 -0800 (PST) Date: Thu, 19 Feb 2004 15:52:27 -0800 (PST) From: Stephan Szabo To: Edmund Bacon Cc: pgsql-sql@postgresql.org Subject: Re: Help refining/eliminating recursive selects In-Reply-To: <1077232156.23327.10.camel@elb_lx.onesystem.ca> Message-ID: <20040219154507.B63910@megazone.bigpanda.com> References: <1077232156.23327.10.camel@elb_lx.onesystem.ca> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200402/295 X-Sequence-Number: 16985 On Thu, 19 Feb 2004, Edmund Bacon wrote: > > I have the following table: > > create table test ( > id serial primary key, > product integer, > tx_date date, > quantity integer) > > with the following data: > id | product | tx_date | quantity > ----+---------+------------+---------- > 1 | 1 | 2004-01-01 | 10 > 2 | 2 | 2004-01-01 | 8 > 3 | 3 | 2004-01-01 | 7 > 4 | 4 | 2004-01-01 | 12 > 5 | 1 | 2004-01-15 | 9 > 6 | 2 | 2004-01-15 | 12 > 7 | 3 | 2004-01-15 | 8 > 8 | 5 | 2004-01-07 | 15 > > > what I want to do is to find the most recent record for each product in > the table. If you don't mind using a PostgreSQL extension, I think distinct on might help you. Maybe something like the following: select distinct on (product) * from test order by product desc, tx_date desc; This might be helped by an index on (product, tx_date).