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
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));