Simple way to calculate median with MySQL

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

    Here is my way . Of course, you could put it into a procedure :-)

    SET @median_counter = (SELECT FLOOR(COUNT(*)/2) - 1 AS `median_counter` FROM `data`);
    
    SET @median = CONCAT('SELECT `val` FROM `data` ORDER BY `val` LIMIT ', @median_counter, ', 1');
    
    PREPARE median FROM @median;
    
    EXECUTE median;
    

    You could avoid the variable @median_counter, if you substitude it:

    SET @median = CONCAT( 'SELECT `val` FROM `data` ORDER BY `val` LIMIT ',
                          (SELECT FLOOR(COUNT(*)/2) - 1 AS `median_counter` FROM `data`),
                          ', 1'
                        );
    
    PREPARE median FROM @median;
    
    EXECUTE median;
    

提交回复
热议问题