I have a table with 3 colums. Here is an example with just a few entries to demo. The table represents the dates that an item’s price changes. I need a query that will tell me the prices for all the items on a specific date. The specific date may be between price changes. The price changes at midnight, so the date of the change, that is the price from then until and on the day before the previous change:
itemCode datePriceEffective price
AB 2012-01-01 9.99
AB 2012-03-02 10.50
XY 2011-09-20 34.99
I wish to get all the items prices for a given date. There is not an entry for every date, just the dates that the price changes.
so 2012-03-05 would return
AB 10.50
XY 34.99
and 2012-02-27 would return:
AB 9.99
XY 34.99
The SQL query needed to get this escapes me. Answers appreciated.
Edited as answers are going in wrong direction see italics for edit.
You will need to join back to the table as follows:
Note that the CTE is just for this example, you should swap it for your real table.
UPDATE: An alternative approach is to use ROW_NUMBER and PARTITION as follows:
(Substitute this select for the one in the previous query to try it out on the data)