SQL 求中位值

题目
A median is defined as a number separating the higher half of a data set from the lower half.
Query the median of the Northern Latitudes (LAT_N) from STATION and round your answer to decimal places.

Input Format

The STATION table is described as follows:
Field type
ID Number
City varchar2(21)
state varchar2(2)
lat_n number
long_w number
where LAT_N is the northern latitude and LONG_W is the western longitude.

这是一道求中位值的题。
中位值是将所给的一组数从小到大或从大到小排列,奇数个数的话取中间的数字,偶数个数的话取中间两个数的平均数。

解答1
Select round(S.LAT_N,4) mediam from station S
where (select count(Lat_N) from station where Lat_N < S.LAT_N ) = (select count(Lat_N) from station where Lat_N > S.LAT_N)
解答2
select round(s.lat_n,4) from station s
where (select round(count(s.id)/2)-1 from station) = (select count(s1.id) from station s1 where s1.lat_n > s.lat_n);

解答3
SELECT
cast(
(SELECT MAX (lat_n) FROM
( SELECT TOP 50 PERCENT lat_n FROM station ORDER BY lat_n) AS H1)/2
+
( SELECT MIN (lat_n) FROM
( SELECT TOP 50 PERCENT lat_n FROM station ORDER BY lat_n DESC ) AS H2)/2
as numeric(21,4));
解答4
select cast(lat_n as decimal(10,4)) from
(select lat_n, row_number() over (order by lat_n desc) as rnum1 from station) t1
where rnum1 =
(select case when max(rnum)%2=0 then max(rnum)/2
else max(rnum)/2+1 end
from
(select row_number() over (order by lat_n desc) as rnum from station) t)
解答5
SET @N := 0;
SELECT COUNT(*) FROM STATION INTO @TOTAL;
SELECT
ROUND(AVG(A.LAT_N), 4)
FROM (SELECT @N := @N +1 AS ROW_ID, LAT_N FROM STATION ORDER BY LAT_N) A
WHERE
CASE WHEN MOD(@TOTAL, 2) = 0
THEN A.ROW_ID IN (@TOTAL/2, (@TOTAL/2+1))
ELSE A.ROW_ID = (@TOTAL+1)/2
END
;
解答6
set @rowindex := -1; /* 1) creates an index*/
/* 3) the outer query will select the average of the 2(for odd no. of values)/1(for even) values we found in the middle of the sorted array */
select round(avg(lat_n),4)
from
/* 2) the index will increment for each new value of lat_n it finds, and sort them by lat_n
*/
(select @rowindex:=@rowindex+1 as rowindex, lat_n
from station
order by lat_n) as l
where l.rowindex in (floor(@rowindex/2), ceil(@rowindex/2));

posted @ 2021-04-09 13:47  webccaa  阅读(460)  评论(0编辑  收藏  举报