Implementing Harmonic Mean in MySQL
July 4, 2008 3:02 pm Math, Programming, SQL, StatisticsThis turns out to be pretty easy. You might also want to read Implementing Geometric Mean in MySQL.
Why bother blogging something this simple? Because I couldn’t find one pre-made, and that means it’s time to bring my mighty google rank of like negative two to bear to fix the problem.
CREATE TABLE example(val integer); INSERT INTO example VALUES(1),(2),(4),(8),(16); SELECT count(val) / sum(1/val) as hmean from example;
That’s it. You should see output like this:
mysql> CREATE TABLE example(val integer); Query OK, 0 rows affected (0.09 sec) mysql> INSERT INTO example VALUES(1),(2),(4),(8),(16); Query OK, 5 rows affected (0.01 sec) Records: 5 Duplicates: 0 Warnings: 0 mysql> SELECT count(val)/sum(1/val) as hmean from example; +- - - - + | hmean | +- - - - + | 2.5806 | +- - - - + 1 row in set (0.00 sec)
Still haven’t figured out how to do central moments, skewness or kurtosis.

July 4th, 2008 at 3:06 pm
[...] Implementing Geometric Mean in MySQL July 4, 2008 3:06 pm admin Math, Programming, SQL, Statistics This turns out to be pretty easy. You might also want to read Implementing Harmonic Mean in MySQL. [...]
January 13th, 2010 at 9:14 am
In Sql Server you need to create a decimal field for SUM work with fraction numbers:
CREATE TABLE example(val decimal);
Good job!