【问题标题】:Having difficulty with 'with' function and median使用“with”函数和中位数有困难
【发布时间】:2019-11-26 17:02:36
【问题描述】:

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

这是来自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);

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 另外请添加CREATE TABLE 语句来定义Station 表(至少包括LAT_N 列),INSERT 语句以提供示例数据,以及收到的实际错误消息。
  • 添加了实际问题的链接以检查您的答案
  • 感谢您的链接,但如果该网站的条款允许,最好发布内容。否则我必须创建一个帐户才能看到问题(将来看到这个 StackOverflow 问题的其他人也是如此)
  • 你的两个CASE...WHEN条件是一样的。

标签: sql sql-server median with-statement


【解决方案1】:

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

问题看起来是WITH 子句仅适用于它开始的语句。您的原始代码有两个语句。因此WITH 仅适用于第一个,因此您不能select LAT_N from List,因为CTE List 仅针对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;

最后,如果您对计算中位数的各种方法感兴趣,请查看this article

【讨论】:

  • 有道理!谢谢,但你认为我可以用不同的方式使用相同的逻辑吗?
  • 更新答案。
  • 或者您可以将 CASE 逻辑移动到最终的 SELECT 中,如最初设置、交叉连接或交叉/外部应用两个 CTE。
  • @Parfait 你还是得反复使用max(rnk) sn-p,不是吗?
  • max(rnk) as max_rnk 只存在于第二个 CTE 中,但它的列在 final 中使用:SELECT... WHERE rnk = CASE WHEN second_cte.max_rnk ...
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 2020-03-01
  • 2012-03-06
相关资源
最近更新 更多