sql - 使用“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);
解决方案
我的假设是这是针对 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;
最后,如果您对计算中位数的各种方法感兴趣,请查看这篇文章。
推荐阅读
- python - Pycharm无法在pycharm中安装包-非零退出码(一)-
- powershell - 在 PowerShell 脚本中设置服务自动失败
- c# - 使用自动增量字段恢复 MySql 表中已删除的行
- android - 即使我使用生成的签名 APK 也没有安装 APK
- google-apps-script - 如何通过管理 SDK 获得经理的价值
- python-3.x - Python docx 无法从 word(.docx) 中读取项目符号
- sqlalchemy - 使用 DATABASE_URL 使用 sqlalchemy 连接到数据库
- linux - 在 Ubuntu 下将 Stata 输出发送到日志文件
- java - 弹性搜索仅索引数据库中最近添加的记录并忽略以前添加的记录
- reactjs - 使用 React Hooks 重新连接 Web 套接字