create clustered index id_time
on tab1 (id,time)
加入方法
select a1.id,a1.time
a1.value as value,
b1.value as value_lag,
c1.value as value_lead
into tab2
from tab1 a1
left join tab1 b1
on a1.id = b1.id
and a1.time-1= b1.time
left join tab1 c1
on a1.id = c1.id
and a1.time+1 = c1.time
使用SET STATISTICS TIME, IO ON生成的IO统计信息:
这是连接方法的执行计划。
窗口函数方法
select id, time, value,
lag(value,1) over(partition by id order by id,time) as value_lag,
lead(value,1) over(partition by id order by id,time) as value_lead
into tab2
from tab1
(只通过时间进行排序可以节省0.5秒。)
这是窗口函数方法的执行计划。
IO统计信息
[![Statistics for Window function method 4]](https://istack.dev59.com/IjuQW.webp)
我检查了
sample_orig_month_1999中的数据,看起来原始数据按id和time排序得很好。这是性能差异的原因吗?
似乎连接方法比窗口函数方法有更多的逻辑读取,而前者的执行时间实际上更短。这是因为前者具有更好的并行性吗?
我喜欢窗口函数方法,因为代码简洁,有没有办法加快它在这个特定问题上的速度?
我正在使用Windows 10 64位上的SQL Server 2016。


