Simple way to calculate median with MySQL

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

    I propose a faster way.

    Get the row count:

    SELECT CEIL(COUNT(*)/2) FROM data;

    Then take the middle value in a sorted subquery:

    SELECT max(val) FROM (SELECT val FROM data ORDER BY val limit @middlevalue) x;

    I tested this with a 5x10e6 dataset of random numbers and it will find the median in under 10 seconds.

提交回复
热议问题