Suppose I have a simple SQL table 'products' with four columns: (productId int unsigned, effectiveDate date, price decimal(10,2), quantityAvailable int unsigned) - this is an oversimplification of the real problem, just to illustrate my point.
let's say select * from products where productId=123 returns this:
123 | 2008-08-01 | 10 | 1000
123 | 2008-08-02 | 10 | 500
123 | 2008-08-03 | 20 | 250
123 | 2008-08-04 | 20 | 100
123 | 2008-08-05 | 10 | 2000
123 | 2008-08-06 | 10 | 1000
123 | 2008-08-07 | 10 | 500
It shows how the price and quantity available fluctuated over time.
My question is... What is the simplest query that could tell me... for any product (of course, for the single example above the answer is 2008-08-05) "when was the last date that the price changed to become equal to today's price"?
I started out with the following (note, the "?" character gets replaced by the desired productId, in this case 123, at query execution time):
select min(effectiveDate) from products where price = (select price from products where productId = ? and effectiveDate = (select max(effectiveDate) from products where productId = ?)) and productId = ?;
But that of course returns 2008-08-01 which is the wrong answer.
Is there a nice, short query that can return the correct answer?
Thanks
Tags: