Simple way to calculate median with MySQL

后端 未结 30 1574
北荒
北荒 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

    I just found another answer online in the comments:

    For medians in almost any SQL:

    SELECT x.val from data x, data y
    GROUP BY x.val
    HAVING SUM(SIGN(1-SIGN(y.val-x.val))) = (COUNT(*)+1)/2
    

    Make sure your columns are well indexed and the index is used for filtering and sorting. Verify with the explain plans.

    select count(*) from table --find the number of rows
    

    Calculate the "median" row number. Maybe use: median_row = floor(count / 2).

    Then pick it out of the list:

    select val from table order by val asc limit median_row,1
    

    This should return you one row with just the value you want.

    Jacob

提交回复
热议问题