Re: query: last N price for each product?

From: "Claus Guttesen" <kometen(at)gmail(dot)com>
To: "David Garamond" <davidgaramond(at)gmail(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: query: last N price for each product?
Date: 2008-07-04 12:44:22
Message-ID: b41c75520807040544l3750718cp55fc65a1a633e830@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

> The query for "latest price for each product" goes like this (which I
> can grasp quite easily):
>
> SELECT * FROM price p1
> WHERE ctime=(SELECT MAX(ctime) FROM price p2 WHERE p1.product_id=p2.product_id)
>
> or:
>
> SELECT * FROM price p1
> WHERE NOT EXISTS (SELECT * FROM price p2 WHERE
> p1.product_id=p2.product_id AND p1.ctime < p2.ctime)
>
> but how do yo query for "latest 3 prices for each product"? The
> "price" table contains current price as well as price histories.

Will this work?

SELECT * FROM price p1
WHERE ctime int (SELECT ctime FROM price p2 WHERE
p1.product_id=p2.product_id order by ctime desc limit 3)

--
regards
Claus

When lenity and cruelty play for a kingdom,
the gentlest gamester is the soonest winner.

Shakespeare

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Frank Bax 2008-07-04 12:55:58 Re: query: last N price for each product?
Previous Message David Garamond 2008-07-04 12:35:57 query: last N price for each product?