Simple way to calculate median with MySQL

后端 未结 30 1572
北荒
北荒 2020-11-22 04:20

What\'s the simplest (and hopefully not too slow) way to calculate the median with MySQL? I\'ve used AVG(x) for finding the mean, but I\'m having a hard time fi

30条回答
  •  没有蜡笔的小新
    2020-11-22 04:41

    Unfortunately, neither TheJacobTaylor's nor velcrow's answers return accurate results for current versions of MySQL.

    Velcro's answer from above is close, but it does not calculate correctly for result sets with an even number of rows. Medians are defined as either 1) the middle number on odd numbered sets, or 2) the average of the two middle numbers on even number sets.

    So, here's velcro's solution patched to handle both odd and even number sets:

    SELECT AVG(middle_values) AS 'median' FROM (
      SELECT t1.median_column AS 'middle_values' FROM
        (
          SELECT @row:=@row+1 as `row`, x.median_column
          FROM median_table AS x, (SELECT @row:=0) AS r
          WHERE 1
          -- put some where clause here
          ORDER BY x.median_column
        ) AS t1,
        (
          SELECT COUNT(*) as 'count'
          FROM median_table x
          WHERE 1
          -- put same where clause here
        ) AS t2
        -- the following condition will return 1 record for odd number sets, or 2 records for even number sets.
        WHERE t1.row >= t2.count/2 and t1.row <= ((t2.count/2) +1)) AS t3;
    

    To use this, follow these 3 easy steps:

    1. Replace "median_table" (2 occurrences) in the above code with the name of your table
    2. Replace "median_column" (3 occurrences) with the column name you'd like to find a median for
    3. If you have a WHERE condition, replace "WHERE 1" (2 occurrences) with your where condition

提交回复
热议问题