cartodb-postgresql/scripts-available/CDB_EqualIntervalBins.sql

38 lines
1007 B
MySQL
Raw Normal View History

2015-05-08 03:49:35 +08:00
--
-- Calculate the equal interval bins for a given column
--
-- @param in_array A numeric array of numbers to determine the best
-- to determine the bin boundary
--
-- @param breaks The number of bins you want to find.
--
--
-- Returns: upper edges of bins
--
--
2015-05-15 03:32:58 +08:00
CREATE OR REPLACE FUNCTION CDB_EqualIntervalBins ( in_array NUMERIC[], breaks INT ) RETURNS NUMERIC[] as $$
2015-05-08 03:49:35 +08:00
DECLARE
diff numeric;
min_val numeric;
2015-05-15 03:32:58 +08:00
max_val numeric;
2015-05-08 03:49:35 +08:00
tmp_val numeric;
i INT := 1;
reply numeric[];
BEGIN
2015-05-15 03:32:58 +08:00
SELECT min(e), max(e) INTO min_val, max_val FROM ( SELECT unnest(in_array) e ) x WHERE e IS NOT NULL;
diff = (max_val - min_val) / breaks::numeric;
2015-05-08 03:49:35 +08:00
LOOP
2015-05-15 03:32:58 +08:00
IF i < breaks THEN
2015-05-08 03:49:35 +08:00
tmp_val = min_val + i::numeric * diff;
reply = array_append(reply, tmp_val);
i := i+1;
ELSE
2015-05-15 03:32:58 +08:00
reply = array_append(reply, max_val);
2015-05-08 03:49:35 +08:00
EXIT;
END IF;
END LOOP;
RETURN reply;
2015-05-15 03:32:58 +08:00
END;
2015-05-08 03:49:35 +08:00
$$ language plpgsql IMMUTABLE;