How can I write a SQL query that would select the latest recommendation from each analyst for each stock as known on a specific date (e.g. 1/1/10). For example, if the analyst has multiple ratings, but the max(rating_date) is greater than the specified date, it should still return the rating at the max date less than the specified date. So, in the case below at a specified date of 1/1/10, I should still get the rating for John as of 6/9/09 as well as the value for Smith as of 12/5/09.
Here's a data structure:
Stock_Ticker, Analyst_Name, Rating_Date, Rating_Name
G, John, 6/9/09, Hold
G, John, 1/20/10, Sell
G, Smith, 12/5/09, Buy
If I try something like the SQL below, I only get a value if the max date is less than the specified date.
Select Analyst_Ratings.Stock_Ticker,
Analyst_Ratings.Analyst_Name,
Analyst_Ratings.Rating_Name
From Analyst_Ratings
Where Rating_Date In(
Select Max(Rating_Date)
From Analyst_Ratings
Where Rating_date <= '2010-01-01')
group bycondition in your inner query.