Simple way to calculate median with MySQL

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

    I used a two query approach:

    • first one to get count, min, max and avg
    • second one (prepared statement) with a "LIMIT @count/2, 1" and "ORDER BY .." clauses to get the median value

    These are wrapped in a function defn, so all values can be returned from one call.

    If your ranges are static and your data does not change often, it might be more efficient to precompute/store these values and use the stored values instead of querying from scratch every time.

提交回复
热议问题