Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id 467C619BEC28 for ; Mon, 21 May 2012 01:38:48 -0300 (ADT) Received: from mailout02.ims-firmen.de ([213.174.32.97]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1SWKOK-0006Bd-0Z for pgsql-sql@postgresql.org; Mon, 21 May 2012 04:38:46 +0000 Received: from mailin01.ims-firmen.de ([192.168.1.141]) by mailout02.ims-firmen.de with esmtp (envelope-from ) id 1SWKO6-0006rc-kW; Mon, 21 May 2012 06:38:30 +0200 Received: from [213.174.32.192] (helo=oxweb02.ims-firmen.de) by mailin01.ims-firmen.de with esmtpsa (TLSv1:RC4-MD5:128) (envelope-from ) id 1SWKMK-0007Bg-2B; Mon, 21 May 2012 06:36:40 +0200 Date: Mon, 21 May 2012 06:34:52 +0200 (CEST) From: Andreas Kretschmer Reply-To: Andreas Kretschmer To: Jan Bakuwel , pgsql-sql@postgresql.org Message-ID: <1746662999.146825.1337574892585.JavaMail.open-xchange@ox.ims-firmen.de> In-Reply-To: <4FB97B70.6080604@greenpeace.org> References: <4FB7EEC6.1030004@gmx.net> <4FB8B489.3050701@gmx.net> <4FB97B70.6080604@greenpeace.org> Subject: Re: master/detail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Priority: 3 Importance: Medium X-Mailer: Open-Xchange Mailer v6.20.2-Rev7 X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201205/71 X-Sequence-Number: 36619 Jan Bakuwel hat am 21. Mai 2012 um 01:17 geschrieben: > Hi, > > I'm trying to get my head around the following question. As an example > take a table with products: > > productid (pk) > name > > and productprice > > productpriceid (pk) > productid (fk) > pricedate > price > > There are multiple records in productprice for each product as prices > (often) go up and (less often) go down. > > I'm looking for a query that returns the following: > > productid, name, pricedate, current_price, difference > > current_price is the latest (ie. most recent date) price of the product > and difference is the difference in price between the latest price and > the price before the latest. > > Any suggestions how to do this with SQL only? I can make it work with a > function (probably less efficient) but think this should be possible > with SQL too... You can use window-function, in your case something like: test=# select * from productprice ; id | product | pricedate | price ----+---------+------------+------- 1 | 1 | 2012-05-01 | 10 2 | 1 | 2012-05-05 | 15 3 | 1 | 2012-05-10 | 12 4 | 1 | 2012-05-15 | 22 (4 rows) test=*# select id, product, pricedate, price, lead(price) over (partition by product order by pricedate desc), price - (lead(price) over (partition by product order by pricedate desc)) from productprice; id | product | pricedate | price | lead | ?column? ----+---------+------------+-------+------+---------- 4 | 1 | 2012-05-15 | 22 | 12 | 10 3 | 1 | 2012-05-10 | 12 | 15 | -3 2 | 1 | 2012-05-05 | 15 | 10 | 5 1 | 1 | 2012-05-01 | 10 | | (4 rows) Regards, Andreas