Home >Database >Mysql Tutorial >How Can I Efficiently Calculate the Median in MySQL?
Calculating the median (the middle value in a set of numerical data) can be challenging in MySQL. While calculating the mean using AVG(x) is simple, finding the median requires a more complex approach.
To simplify median calculation, MariaDB/MySQL provides the following query:
<code class="language-sql">SELECT AVG(dd.val) as median_val FROM ( SELECT d.val, @rownum:=@rownum+1 as `row_number`, @total_rows:=@rownum FROM data d, (SELECT @rownum:=0) r WHERE d.val is NOT NULL -- 在此处添加任何必要的 WHERE 子句 ORDER BY d.val ) as dd WHERE dd.row_number IN ( FLOOR((@total_rows+1)/2), FLOOR((@total_rows+2)/2) );</code>
This query uses the following techniques:
FLOOR((@total_rows 1) / 2)
and FLOOR((@total_rows 2) / 2)
. The above is the detailed content of How Can I Efficiently Calculate the Median in MySQL?. For more information, please follow other related articles on the PHP Chinese website!