我从来没有写过自己的聚合,只写过存储过程,我需要一些建议。
我想编写一个自定义聚合,它将返回整数行的最大值并将其增加 10。我该怎么做?我试过这个:
CREATE AGGREGATE incremented_max ( v ) (
SFUNC = max,
STYPE = integer,
INITCOND = max + 10
)
但它不起作用。有人可以帮我吗?
我收到错误:
ERROR: syntax error at or near "+"
LINE 4: INITCOND = max + 10
老实说,我不明白它应该如何工作。
以下示例展示了如何使用自定义函数创建聚合:
create function greaterint (int, int)
returns int language sql
as $$
select case when $1 < $2 then $2 else $1 end
$$;
create function intplus10 (int)
returns int language sql
as $$
select $1+ 10;
$$;
create aggregate incremented_max (int) (
sfunc = greaterint,
finalfunc = intplus10,
stype = integer,
initcond = 0
);
select incremented_max(v), max(V)
from (
select 3 as v
union select 10
union select 12
union select 5) alias
Sfunc
是状态转换函数。它在聚合中执行的次数与要聚合的行数相同。它的第一个参数是internal-state
,即到目前为止累计的值。在第一次调用中,该值等于initcond
(or null
if initcond
未定义)。第二个参数是next-data-value
,即下一行的值。在上面的示例中,该函数计算非空正整数的最大值并执行四次(针对四行):
call # internal-state next-data-value result
1 0 (initcond) 3 3 (because 3 > 0)
2 3 10 10 (10 > 3)
3 10 12 12 (12 > 10)
4 12 5 12 (12 > 5)
Finalfunc 在聚合结束时执行一次。它有一个参数(到目前为止计算出的值)并返回聚合的最终(修改后的)结果。在我们的示例中,它只是将聚合结果加 10。
阅读更多内容文档 http://www.postgresql.org/docs/9.4/static/sql-createaggregate.html.
上面的例子只是一种练习。事实上,没有必要定义这样的聚合,因为select max (v + 10)
给出了所需的结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)