Simple way to calculate median with MySQL

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

    After reading all previous ones they didn't match with my actual requirement so I implemented my own one which doesn't need any procedure or complicate statements, just I GROUP_CONCAT all values from the column I wanted to obtain the MEDIAN and applying a COUNT DIV BY 2 I extract the value in from the middle of the list like the following query does :

    (POS is the name of the column I want to get its median)

    (query) SELECT
    SUBSTRING_INDEX ( 
       SUBSTRING_INDEX ( 
           GROUP_CONCAT(pos ORDER BY CAST(pos AS SIGNED INTEGER) desc SEPARATOR ';') 
        , ';', COUNT(*)/2 ) 
    , ';', -1 ) AS `pos_med`
    FROM table_name
    GROUP BY any_criterial
    

    I hope this could be useful for someone in the way many of other comments were for me from this website.

提交回复
热议问题