cartodb-postgresql/scripts-available/CDB_Stats.sql

48 lines
1.2 KiB
MySQL
Raw Normal View History

2015-08-26 10:45:55 +08:00
--
2015-08-26 10:58:31 +08:00
-- Calculate basic statistics of a given dataset
2015-08-26 10:45:55 +08:00
--
2015-08-26 10:58:31 +08:00
-- @param in_array A numeric array of numbers
2015-08-26 10:45:55 +08:00
--
2015-08-26 10:58:31 +08:00
-- Returns: statistical quantity chosen
2015-08-26 10:45:55 +08:00
--
2015-08-26 11:10:26 +08:00
-- References: http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm
2015-08-26 10:45:55 +08:00
--
2015-08-26 11:10:26 +08:00
-- Calculate kurtosis
2015-08-26 10:45:55 +08:00
CREATE OR REPLACE FUNCTION CDB_Kurtosis ( in_array NUMERIC[] ) RETURNS NUMERIC as $$
2015-08-26 10:58:31 +08:00
DECLARE
2015-08-26 10:45:55 +08:00
a numeric;
c numeric;
s numeric;
k numeric;
BEGIN
SELECT AVG(e), COUNT(e)::numeric, stddev(e) INTO a, c, s FROM ( SELECT unnest(in_array) e ) x;
2015-08-26 11:10:26 +08:00
EXECUTE 'SELECT sum(power($1 - e, 4)) / ( $2 * power($3, 4)) - 3
2015-08-26 10:58:31 +08:00
FROM (SELECT unnest($4) e ) x'
2015-08-26 10:45:55 +08:00
INTO k
USING a, c, s, in_array;
RETURN k;
END;
$$ language plpgsql IMMUTABLE;
2015-08-26 10:58:31 +08:00
2015-08-26 11:10:26 +08:00
-- Calculate skewness
2015-08-26 10:58:31 +08:00
CREATE OR REPLACE FUNCTION CDB_Skewness ( in_array NUMERIC[] ) RETURNS NUMERIC as $$
DECLARE
a numeric;
c numeric;
s numeric;
sk numeric;
BEGIN
SELECT AVG(e), COUNT(e)::numeric, stddev(e) INTO a, c, s FROM ( SELECT unnest(in_array) e ) x;
EXECUTE 'SELECT sum(power($1 - e, 3)) / ( $2 * power($3, 3))
FROM (SELECT unnest($4) e ) x'
INTO sk
USING a, c, s, in_array;
RETURN sk;
END;
$$ language plpgsql IMMUTABLE;