I have two tables as follows:
Commodity
---------
Id Name
1 Test
2 SecondTest
CommodityPrice
--------------
Id CommodityID Price EffectiveDate
0 1 0.66 05/01/2011
1 1 1.00 06/01/2011
2 1 1.50 07/01/2011
3 2 3.00 05/01/2011
4 2 5.00 06/01/2011
5 2 10.00 07/01/2011
I’m attempting to write a query with the following output:
Result
-------
Name PriceChange
Test 0.50
SecondTest 5.00
I’ve got this query which gets the most recent price, but it’s not dealing with price differences yet.
SELECT c1.Name, cp1.Price
FROM Commodities c1
INNER JOIN CommodityPrices cp1
ON c1.Id = cp1.CommodityId
WHERE EffectiveDate =
(SELECT MAX(cp2.EffectiveDate)
FROM CommodityPrices cp2
WHERE c1.Id = cp2.CommodityId);
I would like to find the price difference between the two most recent prices for a commodity. Note, that this should ignore prices earlier than the most recent two.
This assumes SQL 2005 or later. Just use ROW NUMBER to assign numbers to the rows and then JOIN
ON a.id = b.id AND b.rn = a.rn - 1.Here’s the sample data that I used
Which produced this output
Note: you could also drop
AND b.rn = a.rn - 1from theJOINand addAND a.rn = 2to theWHERE