prøv dette:
;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'
REDIGER baseret på OPs kommentar:
Jeg tror, at ovenstående forespørgsel med CTE vil have samme forespørgselsplan som afledt tabelversion fra @Remus Rusanu
Men hvis productprice
tabellen er stor, kan du reducere den ved at filtrere efter "OnSale
" som her:
;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'