Simple way to calculate median with MySQL

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

    Takes care about an odd value count - gives the avg of the two values in the middle in that case.

    SELECT AVG(val) FROM
      ( SELECT x.id, x.val from data x, data y
          GROUP BY x.id, x.val
          HAVING SUM(SIGN(1-SIGN(IF(y.val-x.val=0 AND x.id != y.id, SIGN(x.id-y.id), y.val-x.val)))) IN (ROUND((COUNT(*))/2), ROUND((COUNT(*)+1)/2))
      ) sq
    

提交回复
热议问题