Row_Number()和分区按性能帮助

时间:2012-08-24 22:28:52

标签: sql-server sql-server-2008 sql-server-2008-r2 query-performance

我有一张股市移动平均值表,我试图在一天内比较两个值,然后将该值与前一天的相同计算值进行比较。我现在的sql是......当我注释掉定义结果集的最后一个select语句,并运行显示为结果集的最后一个cte时,我在大约15分钟内得到了我的数据。很长,但可管理,因为它将在一夜之间作为插入sproc运行。当我如图所示运行它时,我在40分钟之前,任何结果甚至开始进入。任何想法?它有点慢,到爆炸,可能是添加了ROW_NUMBER() OVER (PARTITION BY) BTW我仍在使用逻辑,这在目前的性能问题上是不可能的。提前谢谢..

编辑:我修改了我的分区,如下所示。

with initialSmas as
(
    select TradeDate, Symbol, Period, Value
    from tblDailySMA
),

smaComparisonsByPer as
(
    select i.TradeDate, i.Symbol, i.Period FastPer, i.Value FastVal, 
        i2.Period SlowPer, i2.Value SlowVal, (i.Value-i2.Value) FastMinusSlow
    from initialSmas i join initialSmas as i2 on i.Symbol = i2.Symbol 
        and i.TradeDate = i2.TradeDate and i2.Period > i.Period
),

smaComparisonsByPerPartitioned as
(
    select ROW_NUMBER() OVER (PARTITION BY sma.Symbol, sma.FastPer, sma.SlowPer
    ORDER BY sma.TradeDate) as RowNum, sma.TradeDate, sma.Symbol, sma.FastPer,
    sma.FastVal, sma.SlowPer, sma.SlowVal, sma.FastMinusSlow
    from smaComparisonsByPer sma
)

select scp.TradeDate as LatestDate, scp.FastPer, scp.FastVal, scp.SlowPer, scp.SlowVal,
    scp.FastMinusSlow, scp2.TradeDate as LatestDate, scp2.FastPer, scp2.FastVal, scp2.SlowPer, 
    scp2.SlowVal, scp2.FastMinusSlow, (scp.FastMinusSlow * scp2.FastMinusSlow) as Comparison
from smaComparisonsByPerPartitioned scp join smaComparisonsByPerPartitioned scp2
on scp.Symbol = scp2.Symbol and scp.RowNum = (scp2.RowNum - 1)

1 个答案:

答案 0 :(得分:0)

1)Partition By和Order By子句中都有一些字段。这没有任何意义,因为每个人都有一个且只有一个值(sma.FastPer,sma.SlowPer)。您可以安全地从窗口函数的Order By部分删除这些字段。

2)假设你已经在“initialSmas i join initialSmas”中拥有足够性能的索引,并且你已经拥有索引(initialSmas.Symbol,initialSmas.Period,initialSmas.TradeDate),你可以做的最好的就是复制smaComparisonsByPer进入临时表,你可以在其中创建一个索引(sma.Symbol,sma.FastPer,sma.SlowPer,sma.TradeDate)