X-Original-To: pgsql-general-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 657FD536FD for ; Sun, 17 Apr 2005 09:52:19 -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 65486-03 for ; Sun, 17 Apr 2005 12:52:14 +0000 (GMT) Received: from m-monitor.net (unknown [207.44.134.28]) by svr1.postgresql.org (Postfix) with ESMTP id 783B35370B for ; Sun, 17 Apr 2005 09:52:13 -0300 (ADT) Received: (qmail 14879 invoked from network); 17 Apr 2005 12:52:17 -0000 Received: from 203-206-51-107.dyn.iinet.net.au (HELO ?127.0.0.1?) (203.206.51.107) by ev1s-207-44-134-28.ev1servers.net with SMTP; 17 Apr 2005 12:52:16 -0000 Message-ID: <42625C61.70303@meerkatsoft.com> Date: Sun, 17 Apr 2005 22:53:53 +1000 From: Alex User-Agent: Mozilla Thunderbird 1.0 (Windows/20041206) X-Accept-Language: en-us, en MIME-Version: 1.0 To: Julian Scarfe Cc: pgsql-general@postgresql.org Subject: Re: SQL Question References: <425FAC67.2050203@meerkatsoft.com> <004a01c5425b$c6b4c500$0600a8c0@Wilbur> In-Reply-To: <004a01c5425b$c6b4c500$0600a8c0@Wilbur> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.037 tagged_above=0 required=5 tests=AWL, FORGED_RCVD_HELO X-Spam-Level: X-Archive-Number: 200504/695 X-Sequence-Number: 76608 Julian Scarfe wrote: > From: "Alex" > >> - How can i select only the newest record for each ProdId ? >> >> 100 | 2005-04-01 >> 200 | 2005-04-01 >> > > DISTINCT ON was made for this and on the similar tables I have > performs rather more efficiently than using a subquery. > > select distinct on (ProdId) ProdId , LastUpdate > from produpdate > order by ProdId , LastUpdate desc; > >> - How can i select to retrieve the last 2 dates in record >> >> 100 | 2005-04-01 | 2005-03-01 >> 200 | 2005-04-01 | 2005-03-01 > > > To get the previous one, my first thought is something like: > > select distinct on (ProdId) ProdId , LastUpdate > from produpdate p1 > where LastUpdate <> ( > select max(LastUpdate ) from produpdate p2 where p2.ProdId = p1.ProdId > ) > order by ProdId , LastUpdate desc ; > > but there may be a much more efficient way of getting the nth result > in general. > > Julian Scarfe > > > ---------------------------(end of broadcast)--------------------------- > TIP 3: if posting/reading through Usenet, please send an appropriate > subscribe-nomail command to majordomo@postgresql.org so that your > message can get through to the mailing list cleanly > > Thanks for the help. will give it a try. Alex