Simple way to calculate median with MySQL

后端 未结 30 1559
北荒
北荒 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:52

    Most of the solutions above work only for one field of the table, you might need to get the median (50th percentile) for many fields on the query.

    I use this:

    SELECT CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
     GROUP_CONCAT(field_name ORDER BY field_name SEPARATOR ','),
      ',', 50/100 * COUNT(*) + 1), ',', -1) AS DECIMAL) AS `Median`
    FROM table_name;
    

    You can replace the "50" in example above to any percentile, is very efficient.

    Just make sure you have enough memory for the GROUP_CONCAT, you can change it with:

    SET group_concat_max_len = 10485760; #10MB max length
    

    More details: http://web.performancerasta.com/metrics-tips-calculating-95th-99th-or-any-percentile-with-single-mysql-query/

提交回复
热议问题