我有一个包含累积活动的月份系列的表格,例如
month | activity
1月15日| 20
2月15日| 22
我在另一个表中也有一系列阈值,例如50,100,200。我需要获得达到阈值的日期,即活动> =阈值。
我想这样做的方法是使用pgsql函数读取阈值表,迭代该游标并将months表读入游标,然后迭代那些行,这些行在阈值为到达。出于性能原因,我不是每次都选择month表中的所有行,而是返回光标的第一行,并使用阈值表中的新值重新迭代。
这是解决问题的明智方法吗?这是我到目前为止 - 我得到了一个
ERROR: cursor "curs" already in use
错误。
CREATE OR REPLACE FUNCTION schema.function()
RETURNS SETOF schema.row_type AS
$BODY$
DECLARE
rec RECORD;
rectimeline RECORD;
notification_threshold int;
notification_text text;
notification_date date;
output_rec schema.row_type;
curs SCROLL CURSOR FOR select * from schema.another_function_returning_set(); -- this is months table
curs2 CURSOR FOR select * from schema.notifications_table;
BEGIN
OPEN curs;
FOR rec IN curs2 LOOP
notification_threshold := rec.threshold;
LOOP
FETCH curs INTO rectimeline; -- this line seems to be the problem - not sure why cursor is closing
IF notification_threshold >= rectimeline.activity_total THEN
notification_text := rec.housing_notification_text;
notification_date := rectimeline.active_date;
SELECT notification_text, notification_date INTO output_rec.notification_text, output_rec.notification_date;
MOVE FIRST from curs;
RETURN NEXT output_rec;
END IF;
END LOOP;
END LOOP;
RETURN;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
答案 0 :(得分:1)
select distinct on (t.threshold) *
from
thresholds t
inner join
months m on t.threshold < m.activity
order by t.threshold desc, m.month