Simple way to calculate median with MySQL

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

    as i just needed a median AND percentile solution, I made a simple and quite flexible function based on the findings in this thread. I know that I am happy myself if I find "readymade" functions that are easy to include in my projects, so I decided to quickly share:

    function mysql_percentile($table, $column, $where, $percentile = 0.5) {
    
        $sql = "
                SELECT `t1`.`".$column."` as `percentile` FROM (
                SELECT @rownum:=@rownum+1 as `row_number`, `d`.`".$column."`
                  FROM `".$table."` `d`,  (SELECT @rownum:=0) `r`
                  ".$where."
                  ORDER BY `d`.`".$column."`
                ) as `t1`, 
                (
                  SELECT count(*) as `total_rows`
                  FROM `".$table."` `d`
                  ".$where."
                ) as `t2`
                WHERE 1
                AND `t1`.`row_number`=floor(`total_rows` * ".$percentile.")+1;
            ";
    
        $result = sql($sql, 1);
    
        if (!empty($result)) {
            return $result['percentile'];       
        } else {
            return 0;
        }
    
    }
    

    Usage is very easy, example from my current project:

    ...
    $table = DBPRE."zip_".$slug;
    $column = 'seconds';
    $where = "WHERE `reached` = '1' AND `time` >= '".$start_time."'";
    
        $reaching['median'] = mysql_percentile($table, $column, $where, 0.5);
        $reaching['percentile25'] = mysql_percentile($table, $column, $where, 0.25);
        $reaching['percentile75'] = mysql_percentile($table, $column, $where, 0.75);
    ...
    

提交回复
热议问题