您將需要加入回表如下:
declare @effdate datetime
set @effdate = CONVERT(datetime,'2012-02-27')
;WITH CTE_DATA as (
select itemCode='AB', datePriceEffective = CONVERT(Datetime,'2012-01-01'), price = 9.99
union all select itemCode='AB', datePriceEffective = CONVERT(Datetime,'2012-03-02'), price = 10.50
union all select itemCode='XY', datePriceEffective = CONVERT(Datetime,'2011-09-20'), price = 34.99
)
select
d.itemcode,
price
from
CTE_DATA d
join (
select
itemcode,
effdate = MAX(datepriceeffective)
from CTE_DATA sub where sub.datepriceeffective <= @effdate
group by itemcode
) x
on x.itemCode = d.itemCode
and x.effdate = d.datePriceEffective
注意,CTE只是在這個例子中,你應該將其交換爲您的真正的表。
UPDATE:另一種方法是使用ROW_NUMBER和分區如下:
SELECT
itemcode,
price
FROM
(
SELECT
itemcode,
price,
rowno = ROW_NUMBER() over (partition by itemcode order by datePriceEffective desc)
from
CTE_DATA
where datePriceEffective <= @effdate
) x
where
rowno = 1
(替代這次選擇了一個在前面的查詢嘗試它的數據)
你有使用日期另一列?因爲您在查詢中提到的日期不會在任何列中看到。 – Virus 2012-04-05 10:20:09