prova questo:
;WITH CurrentPrice AS
(
SELECT productid,max(Date) AS Date
FROM productprice
WHERE date < @DateIn
GROUP BY productid
)
select
p.ProductName,
pp.Price,
pp.Date,
from product p
inner join CurrentPrice pa on p.productid = pa.productid
inner join productprice pp on pa.productid = pp.productid AND pa.Date=pp.Date
where p.producttype = 'OnSale'
MODIFICA in base al commento di OP:
Penso che la query precedente con CTE avrà lo stesso piano di query di versione tabella derivata da @Remus Rusanu
Tuttavia, se il productprice
è grande, potresti volerlo ridurre filtrando per "OnSale
" come qui:
;WITH CurrentPrice AS
(
select
p.productid,
MAX(pp.Date) AS Date
from product p
inner join productprice pp on pa.productid = pp.productid
where p.producttype = 'OnSale' AND pp.date < @DateIn
GROUP BY productid
)
select
p.ProductName,
pp.Price,
pp.Date,
from CurrentPrice pa
inner join product p on pa.productid = p.productid
inner join productprice pp on pa.productid = pp.productid AND pa.Date=pp.Date
where p.producttype = 'OnSale'