I have two tables sharing a common key ‘itemID’, the first table holds the latest price for each itemID, the second table holds the date and value of any change to the itemID price as shown. The tLatestItemPrice table is automatically updated whenever a new entry is put into tPriceHistory table
tLatestItemPrice TABLE
itemID, latestPrice
---------------------
item1 400
item2 75
item3 621
tPriceHistory TABLE
itemID, PriceChangeDate, NewPrice
------------------------------------
item1 Jan 8th 2012 400
item1 Jan 7th 2012 300
item1 Jan 6th 2012 280
item1 Jan 3rd 2012 270
item2 Jan 8th 2012 75
item2 Jan 5th 2012 72
item2 Jan 1st 2012 60
item3 Jan 7th 2012 621
item3 Jan 6th 2012 601
item3 Jan 2nd 2012 598
I want to have a query that returns me the price difference between the latest price in tLatestItemPrice table and the price of the item at a specific date. ie if I ask for the change of price between the latest and the 4th of January I want a query to return the following dataset
itemID Price change from 4th Jan
--------------------------
item1 130 (i.e. 400-270)
item2 15
item3 23
Running mysql Ver 14.14 Distrib 5.5.29, for Linux (x86_64)
This is what it become when you have date stored as string in the table