简体   繁体   English

PostgreSQL用户定义的聚合函数中的直接参数

[英]Direct arguments in PostgreSQL user-defined aggregate functions

I am creating a user-defined aggregate function that needs an additional parameter. 我正在创建一个需要附加参数的用户定义的聚合函数。 More precisely it is a cumulative (aka window) minimum that takes as second parameter a time interval defining the window. 更准确地说,它是一个累计(aka窗口)最小值,它将定义该窗口的时间间隔作为第二个参数。 Since the aggregate function operates on my user-defined data types I have conveyed a dummy example that computes the average of the n last values of a column. 由于聚合函数对用户定义的数据类型进行操作,因此我提供了一个虚拟示例,该示例计算列的n个最后值的平均值。 I am aware that I can solve this dummy problem in PostgreSQL but the purpose of the example is only to highlight my problem. 我知道我可以在PostgreSQL中解决这个虚拟问题,但是示例的目的只是为了突出我的问题。

CREATE FUNCTION lastNavg_transfn(state integer[], next integer, n integer)
    RETURNS integer[] AS $$
    BEGIN
        RETURN array_append(state, next);
    END;
    $$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE;

CREATE FUNCTION lastNavg_finalfn(state integer[], n integer)
    RETURNS float AS $$
    DECLARE
        card integer;
        count float;
        sum float;
    BEGIN
        count := 0;
        sum := 0;
        card := array_length(state, 1);
        FOR i IN greatest(1,card-n+1)..card
        LOOP 
            sum := sum + state[i];
            count := count + 1;
        END LOOP;
        RETURN sum/count;
    END;
    $$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE;

CREATE AGGREGATE lastNavg(integer, integer) (
    SFUNC = lastNavg_transfn,
    STYPE = integer[],
    INITCOND = '{}',
    FINALFUNC = lastNavg_finalfn,
    PARALLEL = SAFE
);

I receive the following error 我收到以下错误

ERROR: function lastnavg_finalfn(integer[]) does not exist
SQL state: 42883

How to tell PostgreSQL that my final function also needs a direct parameter? 如何告诉PostgreSQL我的最终函数也需要一个直接参数? I am working on PostgreSQL 10.1. 我正在使用PostgreSQL 10.1。 I know that according to the documentation direct parameters are only allowed for ordered-set aggregates , but I would also need a direct parameter for "normal" aggregates. 我知道根据文档,直接参数仅适用于有序集合 ,但我也需要直接参数用于“常规”聚合。

You could define an aggregate with two arguments and supply your additional parameter as constant second argument. 您可以定义带有两个参数的集合,并提供其他参数作为常量第二个参数。

The SFUNC simply stores the second argument eg as 0-th element of the STYPE integer array. SFUNC只是将第二个参数存储为例如STYPE整数数组的第0个元素。

FINALFUNC has only a single argument and gets n from the 0-th element of the array. FINALFUNC只有一个参数,并且从数组的第0个元素中获取n

If you need a second argument that is not an integer, define a composite type and use that as STYPE . 如果需要第二个非整数参数,请定义一个复合类型并将其用作STYPE

Not pretty, but it should do the trick. 不漂亮,但是应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM