【问题标题】:SQL - Function to return the next value of an array if it doesn't existSQL - 如果数组不存在,则返回数组的下一个值的函数
【发布时间】:2019-03-28 18:21:22
【问题描述】:

我正在尝试使用 3 个参数构建一个函数(在 PostgreSQL 9.6.11 上):

  • 有序值列表(整数数组)
  • 值(整数)
  • 减法(整数)

目标:如果(值-减法)在数组中->返回(值-减法)。 如果没有,我想返回数组中可用的下一个值(下一个位置)

例如我有这个数组 [2010, 2009, 2008, 2007, 2006, 1999]

如果我的 value = 2008 并且 substract = 2,我希望返回 2006(2006 在数组中)

如果我的 value = 2008 并且 substract = 3,我希望返回 1999(2005 不在数组中,下一个可用的值是 1999)

现在,我在这里:

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);

感谢帮助!

【问题讨论】:

  • 这里有一些隐含的假设,也有一些模棱两可的地方。 1)。数组 always 中的值是否按顺序排列,并且按降序排列? 2)。如果您有array = [10, 8, 6, 4, 2], value = 9, subtract = 4,我假设所需的回报应该是4? 3)。如果正确的话,不就是返回数组中小于等于value - subtract的最大值吗? (意思是数组的顺序无关?)
  • 是的,数组中的值总是降序排列,如果值-减法不在数组中,我取小于或等于值-减法的最大值(所以我有a_horse_with_no_name 函数中的一个条件:"AND t.v != value - substract" 来做)

标签: sql postgresql


【解决方案1】:

您可以使用 SQL 函数来执行此操作,无需 PL/pgSQL:

CREATE OR REPLACE FUNCTION check_year_exist(liste INT[], value integer, substract integer)
 RETURNS integer
AS 
$function$
  select max(v)
  from unnest(liste) as t(v)
  where t.v <= value - substract;
$function$
 LANGUAGE sql;

unnest 将所有值作为行返回,where 子句将其限制为小于value - substract 结果的值,然后返回最大数。如果与value - substract相同,则返回,否则为下一个最高值。

SELECT check_year_exist(array[2010, 2009, 2008, 2007, 2006, 1999], 2008, 3);

返回1999

SELECT check_year_exist(array[2010, 2009, 2008, 2007, 2006, 1999], 2008, 2);

返回2006

【讨论】:

    猜你喜欢
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    相关资源
    最近更新 更多