SQL Server Join – How to Join by Most Recent Preceding Date

join;sql serversql-server-2008-r2t-sql

Imagine I have a database with historic price data and a second table with dates

Item | Price | Date               Customer | Item | date
-------------------------         ---------------------------
   A | 2.49$ | 2014-09-01                1 |    A | 2014-08-27
   B | 1.29$ | 2014-09-01                2 |    A | 2014-09-02
   A | 2.99$ | 2014-08-25                
   B | 1.39$ | 2014-08-26

A new row was entered into the price history table every time the price changed.

How can I (efficiently) join the two tables so that I can get the price each customer had to pay on that day?

SQLFiddle

Best Answer

select *
from dbo.Sales s
  cross apply (
  select top (1) *
  from dbo.PriceHistory ph where ph.itemId = s.ItemId and ph.Date <= s.Date
  order by ph.Date desc
) ca;