首页 > 解决方案 > 使用“with”函数和中位数有困难

问题描述

下面的代码应该输出集合的中位数。你能告诉我哪里出错了吗?

这是hackerrank的原始问题:

https://www.hackerrank.com/challenges/weather-observation-station-20/problem

Declare @max_lat int; 
With List as
(
Select LAT_N,Row_number() over (order by LAT_N) as rnk
from Station)
set @max_lat= (select max(rnk) from List);
select LAT_N from List
where rnk= ( case 
                when @max_lat%2=0 then @max_lat/2
                when @max_lat%2=0 then (@max_lat/2)+1
                else (@max_lat+1)/2
                end);

标签: sqlsql-servermedianwith-statement

解决方案


我的假设是这是针对 Microsoft SQL Server 的。

问题看起来是该WITH子句仅适用于它开始的语句。您的原始代码有两个语句。因此WITH仅适用于第一个,因此您不能select LAT_N from List,因为 CTEList仅针对set @max_lat=语句定义。

为避免此问题,请使用第二个 CTE 而不是“临时变量”:

With List as
(
Select LAT_N,Row_number() over (order by LAT_N) as rnk
from #Station),
MaxLat as ( select max(rnk) as max_lat from List )
select LAT_N from List
    INNER JOIN MaxLat 
    ON List.rnk= case 
               when MaxLat.max_lat%2 = 0 then MaxLat.max_lat/2
-- I'm leaving this here because it was in the OP but I don't understand why 
-- there are two when conditions that are the same
               when MaxLat.max_lat%2 = 0 then (MaxLat.max_lat/2)+1
               else (MaxLat.max_lat+1)/2
           end;

最后,如果您对计算中位数的各种方法感兴趣,请查看这篇文章


推荐阅读