在自定义聚合函数postgresql中查找最小值或最大值

Find Min Or Max in custom aggregate function postgresql

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

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

问题是,它没有按预期工作。问题是什么?

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

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

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

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

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

经过这些更改,它似乎按预期工作:https://rextester.com/FTWB14034