D
D
des1roer2015-05-26 11:45:56
PostgreSQL
des1roer, 2015-05-26 11:45:56

Postgres math mean?

suppose there is a table where x corresponds to y
, you need to find the arithmetic mean for any number of xy pairs, the
formula will be like this

sum(x) = x1+x2
avg(y) = ((x1*y1)+(x2*y2))/(x1+x2)

Can this be done in postgres?
jjj9R.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Olenin, 2015-05-26
@vahvarh

From: https://wiki.postgresql.org/wiki/Aggregate_Median
CREATE OR REPLACE FUNCTION _final_median(numeric[])
RETURNS numeric AS
$$
SELECT AVG(val)
FROM (
SELECT val
FROM unnest($1) val
ORDER BY 1
LIMIT 2 - MOD(array_upper($1, 1), 2)
OFFSET CEIL(array_upper($1, 1) / 2.0) - 1
) sub;
$$
LANGUAGE 'sql' IMMUTABLE;
CREATE AGGREGATE median(numeric) (
SFUNC=array_append,
STYPE=numeric[],
FINALFUNC=_final_median,
INITCOND='{}'
);
SELECT median(num_value) AS median_value FROM t;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question