2.sql 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. do $$
  2. begin
  3. create table if not exists temperature_adjustments
  4. (
  5. id serial primary key,
  6. temperature numeric,
  7. adjustment numeric
  8. );
  9. if exists(select from temperature_adjustments limit 1) then
  10. raise notice 'Temperature_adjustments';
  11. else
  12. insert into temperature_adjustments(temperature, adjustment)
  13. values
  14. (0, 0), (5, 0.5), (10, 1), (15, 1), (20, 1.5), (25, 2), (30, 3.5), (40, 4.5);
  15. end if;
  16. if not exists(select from pg_type where typname = 'interpolation') then
  17. create type interpolation as (temperature_b numeric, temperature_t numeric, adjustment_b numeric, adjustment_t numeric, temperature numeric);
  18. end if;
  19. create or replace function calc_interpolation(temp1 numeric)
  20. returns interpolation
  21. language plpgsql as $func$
  22. declare interp interpolation;
  23. begin
  24. select temperature_b, temperature_t, adjustment_b, adjustment_t, temp1 as interpolation into interp from
  25. (select temperature as temperature_b, adjustment as adjustment_b from temperature_adjustments where temperature <= temp1 order by temperature desc limit 1)
  26. full join
  27. (select temperature as temperature_t, adjustment as adjustment_t from temperature_adjustments where temperature >= temp1 order by temperature limit 1)
  28. on true limit 1;
  29. return interp;
  30. end;
  31. $func$;
  32. end $$;
  33. do $$
  34. begin
  35. create or replace function calc_adjustment(interp interpolation)
  36. returns numeric
  37. language plpgsql as $func$
  38. declare adjustment numeric;
  39. begin
  40. if interp.temperature_b = interp.temperature_t then
  41. select 0 into adjustment;
  42. elseif interp.temperature_b = interp.temperature or interp.temperature_t is null then
  43. select interp.adjustment_b into adjustment;
  44. elseif interp.temperature_t = interp.temperature or interp.temperature_b is null then
  45. select intermp.adjustment_t into adjustment;
  46. else
  47. select interp.adjustment_b+((interp.temperature - interp.temperature_b) / (interp.temperature_t - interp.temperature_b)) * (interp.adjustment_t - interp.adjustment_b)
  48. into adjustment;
  49. end if;
  50. return adjustment;
  51. end;
  52. $func$;
  53. end $$;