The purpose of this query is to bring back products and their prices for products on sale and the price should be from the date closest but not equal to the date passed in, essentially the most recent price available. There are not price records for every day. Something feels a little wrong about having the aggregate select statement in the where clause. Is there a better way to do this? Maybe in the join criteria?
select
p.ProductName,
pp.Price,
pp.Date,
from product p
inner join productprice pp on p.productid = pp.productid
where
pp.evaluationdate = (select max(Date) from productprice
where productid = p.productid
and date < @DateIn)
and p.producttype = 'OnSale'
The actually query is a little more complicated but this is essentially the problem. Thanks for your input.
EDIT There will be more than one product returned
EDIT I'm experimenting with both @Remus Rusanu's and @km's suggestions (although @Remus Rusanu removed his) all three, including my original, seem to be about the same in terms of performance. I'm trying to decide if one offers a benefit over the others in some other intangible way i.e. maintenance, self documenting etc. as this will be maintained by someone else. Thanks again.