我有一张股票市场移动平均值表,我试图在一天内比较两个值,然后将该值与前一天的相同计算值进行比较。我的 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)