Simple way to calculate median with MySQL

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

    MySQL has supported window functions since version 8.0, you can use ROW_NUMBER or DENSE_RANK (DO NOT use RANK as it assigns the same rank to same values, like in sports ranking):

    SELECT AVG(t1.val) AS median_val
      FROM (SELECT val, 
                   ROW_NUMBER() OVER(ORDER BY val) AS rownum
              FROM data) t1,
           (SELECT COUNT(*) AS num_records FROM data) t2
     WHERE t1.row_num IN
           (FLOOR((t2.num_records + 1) / 2), 
            FLOOR((t2.num_records + 2) / 2));
    

提交回复
热议问题