如何用case来计算mysql的中位数

时间:2018-03-04 09:34:11

标签: mysql median case-when

我有一个名为station的表,其中包含LAT_N列。我想获得LAT_N的中位数。

所以这是我的问题:

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;

1 个答案:

答案 0 :(得分:0)

尝试以下查询:

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) );