Implementing Harmonic Mean in MySQL

3:02 pm Math, Programming, SQL, Statistics

This 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.

2 Responses

  1. Implementing Geometric Mean in MySQL | Full of BS Says:

    [...] 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. [...]

  2. Henrique Dias Says:

    In Sql Server you need to create a decimal field for SUM work with fraction numbers:

    CREATE TABLE example(val decimal);

    Good job!

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.