简体   繁体   中英

How to calculate median in mysql by using case when

I have a table named station having a column LAT_N . I am trying to get the median of LAT_N .

So here is my query:

select 
case when count(Lat_N)%2=0 then (select (Lat_N from station limit (1,ceil(count(Lat_N)/2))+ select (Lat_N from station limit (1,floor(count(Lat_N)/2)))))
else (Select Lat_N from station limit(1,floor(count(Lat_N)/2)+1))
end
from station;

Try following query:

SELECT avg(tmp1.LAT_N) as median_LAT FROM (
SELECT @rownum:=@rownum+1 as row_number, s.val
  FROM station s,  (SELECT @rownum:=0) r
  ORDER BY s.LAT_N
) as tmp1, 
(
  SELECT count(*) as total_rows
  FROM station s
) as tmp2
AND tmp1.row_number in ( floor((total_rows+1)/2), floor((total_rows+2)/2) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM