为 Postgres 编写自定义聚合函数
我想编写一个聚合函数,返回格式如下的文本: min ->整数列的最大值,其中 min 和 max 是该列的最小值和最大值。 例如:
SELECT min_to_max(val) FROM (VALUES(5),(3),(6),(7),(9),(10),(7)) t(val);
会返回
min_to_max
-----------
3 -> 10
我尝试使用游标编写,但我认为使用自定义聚合会更好,但我不知道如何编写自定义聚合。
我所做的是编写一个正常的函数:
create or replace function min_to_max()
returns varchar
language plpgsql
as
$$
declare
answer varchar;
begin
select MIN(val) || '->' || max(val)
into answer
from abc;
return answer;
end;
$$;
I want to write an aggregate function that returns a text formatted like: min -> max for an integer column, where
min and max are minimum and maximum values of that column.
For example:
SELECT min_to_max(val) FROM (VALUES(5),(3),(6),(7),(9),(10),(7)) t(val);
would return
min_to_max
-----------
3 -> 10
I tried writing using a cursor but I think using a custom aggregate would be much better but I'm clueless how to write a custom aggregate.
What I have done is written a normal function:
create or replace function min_to_max()
returns varchar
language plpgsql
as
$
declare
answer varchar;
begin
select MIN(val) || '->' || max(val)
into answer
from abc;
return answer;
end;
$;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么需要聚合函数? MIN() 和 MAX() 工作正常:
Why do you need an aggregate function? MIN() and MAX() work fine:
正如您所怀疑的,您尝试了一个标准函数,但这只是定义聚合的一部分。用户定义的聚合基本上需要定义(创建聚合)和2个函数,一个定义状态到状态转换的函数和一个处理最终结果生成的函数。 (查看演示)
As suspected you attempted a standard function, however this is only part of defining an aggregate. User defined aggregate requires basically the definition (create aggregate) and 2 functions, one function to define the state-to-state transition and one function to handle the production of the final result. (see demo)