tags:

views:

125

answers:

2

Suppose I have the following table definition :

CREATE TABLE x (i serial primary key, value integer not null);

I want to calculate the MEDIAN of "value" (not the AVG). The median is a value that divides the set in two subsets containing the same number of elements. If the number of elements is even, the median is the average of the biggest value in the lowest segment and the lowest value of the biggest segment. (see wikipedia for more details)

Here is how i manage to calculate the MEDIAN but i guess there must be a better way :

SELECT AVG(values_around_median) AS median
  FROM (
    SELECT
       DISTINCT(CASE WHEN FIRST_VALUE(above) OVER w2 THEN MIN(value) OVER w3 ELSE MAX(value) OVER w2 END)
        AS values_around_median
      FROM (
        SELECT LAST_VALUE(value) OVER w AS value,
               SUM(COUNT(*)) OVER w > (SELECT count(*)/2 FROM x) AS above
          FROM x
          GROUP BY value
          WINDOW w AS (ORDER BY value)
          ORDER BY value
        ) AS find_if_values_are_above_or_below_median
      WINDOW w2 AS (PARTITION BY above ORDER BY value DESC),
             w3 AS (PARTITION BY above ORDER BY value ASC)
    ) AS find_values_around_median

Any ideas ?

+1  A: 

I think you want the MEDIAN value. This is either the middle value or the average of the middle two. There's a whole discussion about it elsewhere on Stack Overflow:

http://stackoverflow.com/questions/1291152/simple-way-to-calculate-median-with-mysql

Jochem
postgres sql will have a better way than mysql as it supports analytic functions and user defined aggregates such as http://wiki.postgresql.org/wiki/Aggregate_Median
Martin Smith
+4  A: 

Indeed there IS an easier way. In Postgres you can define your own aggregate functions. I posted functions to do median as well as mode and range to the PostgreSQL snippets library a while back.

http://wiki.postgresql.org/wiki/Aggregate_Median

Scott Bailey