coba ini:
;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'
EDIT berdasarkan komentar OP:
Saya pikir kueri di atas dengan CTE akan memiliki rencana kueri yang sama dengan versi tabel turunan dari @Remus Rusanu
Namun, jika productprice
tabel besar, Anda mungkin ingin menguranginya dengan memfilter berdasarkan "OnSale
" seperti di sini:
;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'