我正在使用 Postgres 9.2。
我有以下问题:
Time | Value | Device -- Sum should be
1 v1 1 v1
2 v2 2 v1 + v2
3 v3 3 v1 + v2 + v3
4 v4 2 v1 + v4 + v3
5 v5 2 v1 + v5 + v3
6 v6 1 v6 + v5 + v3
7 v7 3 v6 + v5 + v3
本质上,总和需要跨越 N 个设备中每个设备的最新时间值。在上面的示例中,有 3 个设备。
我尝试了几种使用窗口函数的方法,但均未成功。我已经编写了一个存储过程来满足我的需要,但它很慢。缓慢可能是我对 plpgsql 缺乏经验。
CREATE OR REPLACE FUNCTION timeseries.combine_series(id int[], startTime timestamp, endTime timestamp)
RETURNS setof RECORD AS $$
DECLARE
retval double precision = 0;
row_data timeseries.total_active_energy%ROWTYPE;
maxCount integer = 0;
sz integer = 0;
lastVal double precision[];
v_rec RECORD;
BEGIN
SELECT INTO sz array_length($1,1);
FOR row_data IN SELECT * FROM timeseries.total_active_energy WHERE time >= startTime AND time < endTime AND device_id = ANY($1) ORDER BY time
LOOP
retval = row_data.active_power;
for i IN 1..sz LOOP
IF $1[i]=row_data.device_id THEN
lastVal[i] = row_data.active_power;
ELSE
retval = retVal + COALESCE(lastVal[i],0);
END IF;
END LOOP;
SELECT row_data.time, retval into v_rec;
return next v_rec;
END LOOP;
return ;
END;
$$ LANGUAGE plpgsql;
称呼:
select * from timeseries.combine_series('{552,553,554}'::int[], '2013-05-01'::timestamp, '2013-05-02'::timestamp)
AS (t timestamp with time zone, val double precision);
样本数据
CREATE OR REPLACE TEMP TABLE t (ts int, active_power real, device_id int, should_be int);
INSERT INTO t VALUES
(1,2,554,2)
,(2,3,553,5)
,(3,9,553,11)
,(4,7,553,9)
,(5,6,552,15)
,(6,8,554,21)
,(7,5,553,19)
,(8,7,553,21)
,(9,6,552,21)
,(10,7,552,22)
;