Re: selecting latest record - Mailing list pgsql-sql

From A. Kretschmer
Subject Re: selecting latest record
Date
Msg-id 20090922100846.GD5415@a-kretschmer.de
Whole thread Raw
In response to selecting latest record  (Louis-David Mitterrand <vindex+lists-pgsql-sql@apartia.org>)
Responses Re: selecting latest record
List pgsql-sql
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)


pgsql-sql by date:

Previous
From: Louis-David Mitterrand
Date:
Subject: Re: selecting latest record
Next
From: Rob Sargent
Date:
Subject: Re: selecting latest record