Pass extra parameter to PostgreSQL aggregate final function

前端 未结 3 505
甜味超标
甜味超标 2020-12-18 09:39

Is the only way to pass an extra parameter to the final function of a PostgreSQL aggregate to create a special TYPE for the state value?

e.g.:

CREATE         


        
3条回答
  •  情话喂你
    2020-12-18 10:11

    You can define an aggregate with more than one parameter.

    I don't know if that solves your problem, but you could use it like this:

    CREATE OR REPLACE FUNCTION myaggsfunc(integer, integer, text) RETURNS integer
       IMMUTABLE STRICT LANGUAGE sql AS
    $f$
       SELECT CASE $3
               WHEN '+' THEN $1 + $2
               WHEN '*' THEN $1 * $2
               ELSE NULL
            END
    $f$;
    
    CREATE AGGREGATE myagg(integer, text) (
       SFUNC = myaggsfunc(integer, integer, text),
       STYPE = integer
    );
    

    It could be used like this:

    CREATE TABLE mytab
       AS SELECT * FROM generate_series(1, 10) i;
    
    SELECT myagg(i, '+') FROM mytab;
    
     myagg 
    -------
        55
    (1 row)
    
    SELECT myagg(i, '*') FROM mytab;
    
      myagg  
    ---------
     3628800
    (1 row)
    

提交回复
热议问题