这是一种利用该工具将聚合函数用作窗口函数的方法。聚合函数将最后 15 分钟的观察值与当前运行总数一起保存在一个数组中。状态转换函数将落后于 15 分钟窗口的元素从数组中移出,并推送最新的观察结果。最后一个函数简单地计算阵列中的平均温度。
现在,至于这是否有好处……这取决于。它侧重于postgresql的plgpsql-execution部分而不是database-access部分,我自己的经验是plpgsql并不快。如果您可以轻松地对表进行查找以查找每个观察的前 15 分钟的行,那么自联接(如@danihp 答案)会做得很好。然而,这种方法可以处理来自一些更复杂的来源的观察,这些查找是不切实际的。与以往一样,在您自己的系统上试用和比较。
-- based on using this table definition
create table observation(id int primary key, timestamps timestamp not null unique,
temperature numeric(5,2) not null);
-- note that I'm reusing the table structure as a type for the state here
create type rollavg_state as (memory observation[], total numeric(5,2));
create function rollavg_func(state rollavg_state, next_in observation) returns rollavg_state immutable language plpgsql as $$
declare
cutoff timestamp;
i int;
updated_memory observation[];
begin
raise debug 'rollavg_func: state=%, next_in=%', state, next_in;
cutoff := next_in.timestamps - '15 minutes'::interval;
i := array_lower(state.memory, 1);
raise debug 'cutoff is %', cutoff;
while i <= array_upper(state.memory, 1) and state.memory[i].timestamps < cutoff loop
raise debug 'shifting %', state.memory[i].timestamps;
i := i + 1;
state.total := state.total - state.memory[i].temperature;
end loop;
state.memory := array_append(state.memory[i:array_upper(state.memory, 1)], next_in);
state.total := coalesce(state.total, 0) + next_in.temperature;
return state;
end
$$;
create function rollavg_output(state rollavg_state) returns float8 immutable language plpgsql as $$
begin
raise debug 'rollavg_output: state=% len=%', state, array_length(state.memory, 1);
if array_length(state.memory, 1) > 0 then
return state.total / array_length(state.memory, 1);
else
return null;
end if;
end
$$;
create aggregate rollavg(observation) (sfunc = rollavg_func, finalfunc = rollavg_output, stype = rollavg_state);
-- referring to just a table name means a tuple value of the row as a whole, whose type is the table type
-- the aggregate relies on inputs arriving in ascending timestamp order
select rollavg(observation) over (order by timestamps) from observation;