0

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;
tyro
  • 1,298
  • 1
  • 15
  • 30
Jing Hong
  • 83
  • 1
  • 6

1 Answers1

0

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) );
Harshil Doshi
  • 3,419
  • 3
  • 11
  • 30