Postgresql Plpgsql-在记录集上迭代多次

Postgresql Plpgsql-在记录集上迭代多次,postgresql,cursor,plpgsql,Postgresql,Cursor,Plpgsql,我有一张表,表中有几个月的累积活动,例如 month|活动 2015年1月20日 2月15日至22日 我在另一个表中也有一系列阈值,例如50、100、200。我需要获取达到阈值的日期,即活动>=阈值 我想这样做的方式是使用一个pgsql函数,它读取阈值表,迭代该游标,并在月份表中读取一个游标,然后迭代这些行,计算出达到阈值的月份。出于性能原因,我不会每次都选择months表中的所有行,而是返回游标中的第一行,使用thresholds表中的新值重新迭代 这是解决问题的明智方法吗?这就是我到目前为止

我有一张表,表中有几个月的累积活动,例如

month|活动

2015年1月20日

2月15日至22日

我在另一个表中也有一系列阈值,例如50、100、200。我需要获取达到阈值的日期,即活动>=阈值

我想这样做的方式是使用一个pgsql函数,它读取阈值表,迭代该游标,并在月份表中读取一个游标,然后迭代这些行,计算出达到阈值的月份。出于性能原因,我不会每次都选择months表中的所有行,而是返回游标中的第一行,使用thresholds表中的新值重新迭代

这是解决问题的明智方法吗?这就是我到目前为止所拥有的——我正在得到一份工作
错误:光标“curs”已在使用中
错误

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
选择distinct on(t.阈值)*
从…起
阈值t
内连接
t.阈值
Doh!我原以为这样做可以奏效,但我拒绝了——永远不要低估sql的威力!只有当我将其更改为t.threshold时,它才起作用-假设这与连接有关。另外,
orderby
子句在这里似乎非常重要。请注意自我理解此查询@Stev_k只有当我将它更改为t.threshold确定我的错误时,它才起作用。但后来你不得不改成按t.threshold**desc**排序,是吗?有趣的是,我没有。我本以为这是必要的,因为我认为distinct选择了第一个唯一的条目,但在不改变顺序的情况下,它似乎对我来说没问题——不知道为什么。
select distinct on (t.threshold) *
from
    thresholds t
    inner join
    months m on t.threshold < m.activity
order by t.threshold desc, m.month