Skip to content

Instantly share code, notes, and snippets.

@andy-esch
Created April 4, 2016 20:58
Show Gist options
  • Save andy-esch/f00953760fc63b60c1a9d3a90748ac61 to your computer and use it in GitHub Desktop.
Save andy-esch/f00953760fc63b60c1a9d3a90748ac61 to your computer and use it in GitHub Desktop.
naive stddev bins script
CREATE OR REPLACE FUNCTION CDB_StdDevBins(input numeric[],
num_bins INT DEFAULT 5)
RETURNS NUMERIC[]
AS $$
DECLARE
mean_val numeric;
stddev_val numeric;
out_arr numeric[];
i int;
BEGIN
IF array_length(input, 1) <= num_bins
THEN
RETURN input;
END IF;
SELECT avg(a), stddev(a) INTO mean_val, stddev_val FROM (SELECT unnest(input) as a) x;
FOR i in 1..(num_bins / 2)
LOOP
out_arr := array_append(out_arr, mean_val * i * stddev_val);
END LOOP;
RETURN out_arr;
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment