Skip site navigation (1) Skip section navigation (2)

Re: master/detail

From: "Raj Mathur ( राज =?utf-8?b?IOCkruCkvuCkpeClgeCksA==?=)" <raju(at)linux-delhi(dot)org>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: master/detail
Date: 2012-05-21 03:10:26
Message-ID: 201205210840.26777.raju@linux-delhi.org (view raw or flat)
Thread:
Lists: pgsql-sql
On Monday 21 May 2012, Jan Bakuwel wrote:
> 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...

Something like this ought to do it (not tested):

select latest.price, latest.price - next.price
from
  (select price from productprice where productid = 1
    order by pricedate desc limit 1) latest,
  (select price from productprice where productid  = 1
    order by pricedate desc limit 2 offset 1) next;

Regards,

-- Raj
-- 
Raj Mathur                          || raju(at)kandalaya(dot)org   || GPG:
http://otheronepercent.blogspot.com || http://kandalaya.org || CC68
It is the mind that moves           || http://schizoid.in   || D17F

In response to

pgsql-sql by date

Next:From: Andreas KretschmerDate: 2012-05-21 04:34:52
Subject: Re: master/detail
Previous:From: Jan BakuwelDate: 2012-05-20 23:17:04
Subject: master/detail

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group