pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: A. Kretschmer <andreas.kretschmer@schollglas.com>
To: pgsql-sql@postgresql.org
Subject: Re: selecting latest record
Date: Tue, 22 Sep 2009 12:08:46 +0200
Message-ID: <20090922100846.GD5415@a-kretschmer.de> (raw)
In-Reply-To: <20090922094457.GA24885@apartia.fr>
References: <20090922094457.GA24885@apartia.fr>

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)



view thread (5+ messages)  latest in thread

Message-ID: <20090922100846.GD5415@a-kretschmer.de>
Permalink:  ../20090922100846.GD5415@a-kretschmer.de/
Also on:    postgresql.org/message-id/20090922100846.GD5415@a-kretschmer.de

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: andreas.kretschmer@schollglas.com
  Subject: Re: selecting latest record
  In-Reply-To: <20090922100846.GD5415@a-kretschmer.de>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox