Calculating the Median with Mysql

后端 未结 7 1730
傲寒
傲寒 2020-12-17 00:38

I\'m having trouble with calculating the median of a list of values, not the average.

I found this article Simple way to calculate median with MySQL

It has a

相关标签:
7条回答
  • 2020-12-17 01:21

    Finding median in mysql using group_concat

    Query:

    SELECT
        IF(count%2=1,
           SUBSTRING_INDEX(substring_index(data_str,",",pos),",",-1),
           (SUBSTRING_INDEX(substring_index(data_str,",",pos),",",-1) 
             + SUBSTRING_INDEX(substring_index(data_str,",",pos+1),",",-1))/2) 
        as median 
    FROM (SELECT group_concat(val order by val) data_str,
          CEILING(count(*)/2) pos,
          count(*) as count from data)temp;
    

    Explanation:

    Sorting is done using order by inside group_concat function

    Position(pos) and Total number of elements (count) is identified. CEILING to identify position helps us to use substring_index function in the below steps.

    Based on count, even or odd number of values is decided.

    • Odd values: Directly choose the element belonging to the pos using substring_index.
    • Even values: Find the element belonging to the pos and pos+1, then add them and divide by 2 to get the median.

    Finally the median is calculated.

    0 讨论(0)
提交回复
热议问题