這是您的查詢:
SELECT ProductId, @PriceDate AS PriceDate, Price
FROM (SELECT fp.*,
ROW_NUMBER() OVER (PARTITION BY ProductId
ORDER BY COALESCE(FromDate, '19000101') DESC, COALESCE(ToDate, '21000101') ASC) AS RowNumber
FROM FactPrices fp
WHERE (FactPrices.FromDate IS NULL OR FactPrices.FromDate <= @PriceDate) AND
(FactPrices.ToDate IS NULL OR FactPrices.ToDate >= @PriceDate)
) A
WHERE A.RowNumber = 1;
的where
子句是一個大的性能殺手。我將建議添加兩個計算列,然後再添加兩個索引。
計算列是:
FromDateNotNull as (coalesce(FromDate, '19000101'))
ToDateNotNull as (coalesce(ToDate, '21000101'))
然後,在創建索引:
(Prices, FromDateNotNull desc, ToDateNotNull asc)
(FromDateNotNull, ToDateNotNull)
然後,寫一個查詢爲:
SELECT ProductId, @PriceDate AS PriceDate, Price
FROM (SELECT fp.*,
ROW_NUMBER() OVER (PARTITION BY ProductId
ORDER BY FromDateNotNull DESC, ToDateNotNull
) AS RowNumber
FROM FactPrices fp
WHERE FromDateNotNull <= @PriceDate AND
ToDateNotNull >= @PriceDate
) A
WHERE A.RowNumber = 1;
你對錶中的任何索引? –
是的,索引不是我的問題。如果有一種方法可以在不使用分析功能的情況下做到這一點,我就會更加流浪。可能會對'tempdb'更友善的東西。這可能是最好的方式,並且由於我擁有大量的數據,我可能不得不忍受它。 – Lock
[** This **](http://dba.stackexchange.com/questions/86415/retrieving-n-rows-per-group)可能會有所幫助。 –