I'm trying to build a function (on PostgreSQL 9.6.11) with 3 parameters :
- list of ordered values (array of integers)
- value (integer)
- substract (integer)
The aim : if (value - substract) is in the array -> return (value - substract). If not, I would like to return the next value available in the array (next position)
For example I have this array [2010, 2009, 2008, 2007, 2006, 1999]
If I have value = 2008 and substract = 2, I expect the return 2006 (2006 is in the array)
If I have value = 2008 and substract = 3, I expect the return 1999 (2005 is not in the array, the next value available is 1999)
For now, I'm here :
CREATE OR REPLACE FUNCTION _fonctions_globales.check_year_exist(liste INT[], value integer, substract integer)
RETURNS integer
LANGUAGE plpgsql
AS $function$
BEGIN
IF EXISTS (SELECT 1 WHERE (value - substract) = ANY(liste)) THEN
return value - substract;
ELSE
return ?;
END IF;
END; $function$
SELECT _fonctions_globales.check_year_exist(array[2010, 2009, 2008, 2007, 2006, 1999], 2008, 3);
Thks for help !
array = [10, 8, 6, 4, 2], value = 9, subtract = 4I'm assuming the desired return should be4? 3). If that's correct, isn't it just a case of return the largest value in the array that is less than or equal tovalue - subtract? (Meaning that the order of the array is irrelevant?)