Simple way to calculate median with MySQL

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

    Building off of velcro's answer, for those of you having to do a median off of something that is grouped by another parameter:

    SELECT grp_field, t1.val FROM (
       SELECT grp_field, @rownum:=IF(@s = grp_field, @rownum + 1, 0) AS row_number,
       @s:=IF(@s = grp_field, @s, grp_field) AS sec, d.val
      FROM data d,  (SELECT @rownum:=0, @s:=0) r
      ORDER BY grp_field, d.val
    ) as t1 JOIN (
      SELECT grp_field, count(*) as total_rows
      FROM data d
      GROUP BY grp_field
    ) as t2
    ON t1.grp_field = t2.grp_field
    WHERE t1.row_number=floor(total_rows/2)+1;
    

提交回复
热议问题