我想加快以下(PostgreSQL)代码,并且我推测它可以帮助摆脱(某些)循环,但是我没有看到方法来做到这一点。欢迎任何关于加速的建议。提前致谢!避免循环计算运行平均值/统计数据列
该代码为不同部分的每个列计算一些统计量(平均值,斜率)。该部分由滑动时间窗(例如60分钟)确定。因此,通过这些我很感兴趣,计算其统计
为每列不同的列如下
- 循环的代码,我依次移动我的时间窗口,并计算在该窗口中的值的统计信息。
for col_name in ..... a list of column names truncate small_table; -- where statistics are temporarily stored for cur in select time from big_table loop execute 'select regr_slope('|| col_name ||', time) as slope,' || ' avg(' || col_name || ') as mean' || ' from big_table where' || ' time <=' || cur.time || ' and time >=' || cur.time-60 into result; execute 'insert into small_table values($1,$2,$3)' using cur.time, result.slope, result.mean; end loop; execute 'update big_table set ' || col_name || '_slope = small_table.slope, ' || col_name || '_mean = small_table.mean ' || ' where big_table.time=small_table.time'; end loop;
small_table
,其中结果被暂时储存,引入避免对big_table
多个更新。
small_table
和big_table
具有相同的结构,但小表的行数少得多。两个表的 列是
time | field_1 | field_2 | field_1_slope | field_1_mean | field_2_slope | field_2_mean
实际上有相当多的列(约50),这可能放缓的另一个因素?
是否BIG_TABLE对时间列的索引? – Laurence
是的。感谢澄清。 –
数据点之间是否存在固定的时间间隔或是随机的? – Laurence