Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 5BFBB62E7C6 for ; Tue, 22 Sep 2009 07:08:58 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 19025-03 for ; Tue, 22 Sep 2009 10:08:50 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from moutng.kundenserver.de (moutng.kundenserver.de [212.227.17.10]) by mail.postgresql.org (Postfix) with ESMTP id 6E080632710 for ; Tue, 22 Sep 2009 07:08:50 -0300 (ADT) Received: from webserv.wug.de ([194.25.154.138]) by mrelayeu.kundenserver.de (node=mrbap1) with ESMTP (Nemesis) id 0MKt2u-1Mq2Ih0j7h-000FuE; Tue, 22 Sep 2009 12:08:48 +0200 Received: from kretschmer by webserv.wug.de with local (Exim 3.36 #1) id 1Mq2Ig-00072L-00 for pgsql-sql@postgresql.org; Tue, 22 Sep 2009 12:08:46 +0200 Date: Tue, 22 Sep 2009 12:08:46 +0200 From: "A. Kretschmer" To: pgsql-sql@postgresql.org Subject: Re: selecting latest record Message-ID: <20090922100846.GD5415@a-kretschmer.de> References: <20090922094457.GA24885@apartia.fr> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <20090922094457.GA24885@apartia.fr> X-OS: Debian/GNU Linux - weil ich es mir Wert bin! User-Agent: Mutt/1.5.9i X-Provags-ID: V01U2FsdGVkX1+BP5l1l65q+oMTRvcHhmHb4P6p8X4qtKXu5om zPiVwwsrxM8W4X03CblPEYXjuyoNrxBgLzqa08ljwC+fMym4QK ZEF21O4OTIt+qkB0G3bew== X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-0.74 tagged_above=-10 required=5 tests=BAYES_20=-0.74 X-Spam-Level: X-Archive-Number: 200909/103 X-Sequence-Number: 33168 In response to Louis-David Mitterrand : > Hi, > > I have a simple table > > price(id_product, price, date) > > which records price changes for each id_product. Each time a price > changes a new tuple is created. > > What is the best way to select only the latest price of each id_product? There are several ways to do that, for instance with DISTINCT ON (only postgresql): test=*# select * from price ; id_product | price | datum ------------+-------+------------ 1 | 10 | 2009-09-01 1 | 12 | 2009-09-10 2 | 11 | 2009-09-10 2 | 8 | 2009-09-13 (4 rows) test=*# select distinct on (id_product) id_product, price from price order by id_product, datum desc; id_product | price ------------+------- 1 | 12 2 | 8 (2 rows) Andreas -- Andreas Kretschmer Kontakt: Heynitz: 035242/47150, D1: 0160/7141639 (mehr: -> Header)