I have an application that keeps track of prices for various products. Prices might change for any given product at any time during any day, and will not change regularly. There is a PriceHistory table that has dated records for all of the prices for the products over time. Users of the application can select a time and date and see what the prices were at that time. I use a query like this to get the "current" prices for all products at any given day and time:
SELECT A.*
FROM `PriceHistory` A
INNER JOIN (
SELECT `BrandKey`, `LocationKey`, `ProductKey`, max(`EffectiveDateTime`) AS MaxUpdateDate
FROM `PriceHistory`
WHERE `EffectiveDateTime` <= '2010-02-22 12:00:00'
GROUP BY `BrandKey`, `LocationKey`, `ProductKey`
) AS B ON
A.`BrandKey` = B.`BrandKey`
AND A.`LocationKey` = B.`LocationKey`
AND A.`ProductKey` = B.`ProductKey`
AND A.`EffectiveDateTime` = B.MaxUpdateDate
Now I need to be able to show users how much the price changed when that price went into effect. So I need to get the two most recent prices for the selected time instead of just one. I'm pretty stumped. I've tried a couple of things and I'm just getting SQL errors because my attempted joins aren't legal. Any help would be appreciated.
I can loop over all the products and get the two most recent prices, but that's taking about 10 seconds for 350 products and 75,000 price rows. I don't necessarily need all products in one query, but running queries for each product won't be fast enough.