在自定义聚合函数postgresql中查找Min或Max

时间:2019-03-06 14:35:53

标签: sql postgresql aggregate plpgsql

我是Postgresql的新手(我在PL / pgSQL中编程,与sql没有太大区别)。 我写了我的客户聚合函数,该函数必须在一个数字数组中找到最小值或最大值。 这是函数汇总代码

CREATE OR REPLACE FUNCTION searchMaxValue (numeric[]) RETURNS numeric AS $$
DECLARE 
i numeric;
maxVal numeric;
BEGIN
maxVal = $1[1];
IF ARRAY_LENGHT($1,1) > 0 THEN --Checking whether the array is empty or  not
   <<confrontoMassimo>>
   FOREACH i IN ARRAY $1 LOOP --Looping through the entire array, passed as parameter
       IF maxVal <= $1[i] THEN
           maxVal := $1[i];
       END IF;
   END LOOP confrontoMassimo;
   ELSE
   RAISE NOTICE 'Invalid parameter % passed to the aggregate function',$1;
   --Raising exception if the parameter passed as argument points to null.
   RAISE EXCEPTION 'Cannot find Max value. Parameter % is null', $1
   USING HINT = 'You cannot pass a null array! Check the passed parameter';

END IF;
RETURN maxVal;
END;
$$ LANGUAGE plpgsql;

 CREATE AGGREGATE searchMaxValueArray (numeric)
(
sfunc = array_append,
stype = numeric[],
finalfunc = searchMaxValue,
initCond = '{}'
);

问题是,它无法按预期运行。问题是什么?

1 个答案:

答案 0 :(得分:2)

如上所述,您的功能中有一个小的错字; ARRAY_LENGHT应该是ARRAY_LENGTH

除此之外,我唯一能看到的问题是在这里:

FOREACH i IN ARRAY $1 LOOP
    IF maxVal <= $1[i] THEN
        ...

FOREACH loop中,目标变量i不是数组索引,而是数组元素本身。换句话说,循环应该是:

FOREACH i IN ARRAY $1 LOOP
    IF maxVal <= i THEN
        maxVal := i;
    END IF;
END LOOP

有了这些更改,它似乎可以正常工作:https://rextester.com/FTWB14034