首页 > 解决方案 > 将存储的公式转换为 PL/pgSQL

问题描述

我在我的数据库中存储了一个公式,该值由我组织中的某些人定义并用于计算平均值。问题是我需要在 PL/pgSQL 过程(postgres)中使用该公式,但语法不同,有些公式是这样的:

if (x >= 0 && x <= 51.999) then 0 
elsif (x > 51.999 && x <= 64.999) then 70 
elsif (x > 64.999 && x <= 90.999) then 100 
elsif (x > 90.999 && x <= 103.999) then 115 
elsif (x > 103.999 && x <= 130) then 130 end

x = 我的价值

我一直在考虑更换,但我不知道这是否是正确的解决方案......所以,我需要你的帮助。谢谢!

标签: postgresqlplpgsql

解决方案


在 PL/pgSQL 语法中:

y := case
 when x between 0 and 51.999 then 0 
 when x between 52 and 64.999 then 70 
 when x between 65 and 90.999 then 100 
 when x between 91 and 103.999 then 115 
 when x between 104 and 130 then 130 
end;

请注意,这between是包容性的。这就是我改变下限的原因。
作为可重用的功能:

create or replace function custom_function(x numeric) returns numeric language sql as
$$
select case
 when x between 0 and 51.999 then 0 
 when x between 52 and 64.999 then 70 
 when x between 65 and 90.999 then 100 
 when x between 91 and 103.999 then 115 
 when x between 104 and 130 then 130 
end::numeric;
$$;

编辑
多个公式。您可以以干净的声明方式定义/更改其中的许多。

create or replace function pg_temp.custom_function(function_name text, x numeric)
returns numeric language sql as
$$
with function_data(fname, range_lo, range_hi, result) as
(
  values
  -- function_a parameter values
  ('function_a', 0,   51.999,  0),
  ('function_a', 52,  64.999,  70),
  ('function_a', 65,  90.999,  100),
  ('function_a', 91,  103.999, 115),
  ('function_a', 104, 130.999, 130),
  -- function_b parameter values 
  ('function_b', 0,   51.999,  10),
  ('function_b', 52,  64.999,  170),
  ('function_b', 65,  90.999,  200),
  ('function_b', 91,  103.999, 215),
  ('function_b', 104, 130.999, 230)
  -- other function names and values
)
select result::numeric 
  from function_data
  where fname = function_name 
  and x between range_lo and range_hi;
$$;

像这样调用函数:

select custom_function('function_a', 100)

推荐阅读