HomeWork20250206_Part2.sql 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. 5. Пример скрипты для расчета интерполяции
  3. ==========================================
  4. */
  5. do $$
  6. declare
  7. var_interpolation interpolation_type;
  8. var_temperature integer default 22;
  9. var_result numeric(8,2) default 0;
  10. var_min_temparure numeric(8,2) default 0;
  11. var_max_temperature numeric(8,2) default 0;
  12. var_denominator numeric(8,2) default 0;
  13. begin
  14. raise notice 'Расчет интерполяции для температуры %', var_temperature;
  15. -- Проверим, возможно температура совпадает со значением в справочнике
  16. if exists (select 1 from public.calc_temperatures_correction where temperature = var_temperature ) then
  17. begin
  18. select correction
  19. into var_result
  20. from public.calc_temperatures_correction
  21. where
  22. temperature = var_temperature;
  23. end;
  24. else
  25. begin
  26. -- Получим диапазон в котором работают поправки
  27. select min(temperature), max(temperature)
  28. into var_min_temparure, var_max_temperature
  29. from public.calc_temperatures_correction;
  30. if var_temperature < var_min_temparure or
  31. var_temperature > var_max_temperature then
  32. raise exception 'Некорректно передан параметр! Невозможно рассчитать поправку. Значение должно укладываться в диаппазон: %, %',
  33. var_min_temparure, var_max_temperature;
  34. end if;
  35. -- Получим граничные параметры
  36. select x0, y0, x1, y1
  37. into var_interpolation.x0, var_interpolation.y0, var_interpolation.x1, var_interpolation.y1
  38. from
  39. (
  40. select t1.temperature as x0, t1.correction as y0
  41. from public.calc_temperatures_correction as t1
  42. where t1.temperature <= var_temperature
  43. order by t1.temperature desc
  44. limit 1
  45. ) as leftPart
  46. cross join
  47. (
  48. select t1.temperature as x1, t1.correction as y1
  49. from public.calc_temperatures_correction as t1
  50. where t1.temperature >= var_temperature
  51. order by t1.temperature
  52. limit 1
  53. ) as rightPart;
  54. raise notice 'Граничные значения %', var_interpolation;
  55. -- Расчет поправки
  56. var_denominator := var_interpolation.x1 - var_interpolation.x0;
  57. if var_denominator = 0.0 then
  58. raise exception 'Деление на нуль. Возможно, некорректные данные в таблице с поправками!';
  59. end if;
  60. var_result := (var_temperature - var_interpolation.x0) * (var_interpolation.y1 - var_interpolation.y0) / var_denominator + var_interpolation.y0;
  61. end;
  62. end if;
  63. raise notice 'Результат: %', var_result;
  64. end $$;