【问题标题】:Getting the Range Value获取范围值
【发布时间】:2018-08-22 14:24:57
【问题描述】:

我有一个查询产生的下表

我想使用 MaxmiumDays 列获得适合上述 269 范围的最佳范围列表。请检查以下输出。

【问题讨论】:

  • “最好”是什么意思?
  • 请不要发布数据图片,提供text
  • @TheImpaler 如果我检查小于 Maxmium 天数,我将获得所有 3 条记录。但按照逻辑,它应该在 365 Maxium Days Record 中。好像大于 30 天但小于 365 ..
  • 您的意思是对于特定的“天”数,您要返回最低的MaximumDays 值,还是返回MaximumDays 最低的行?
  • 您需要提供更多关于您拥有什么和想要什么的信息。我们不知道您正在使用的系统,也无法提供帮助。

标签: sql sql-server sql-server-2008-r2


【解决方案1】:

对于旧版本,您可以使用outer apply

select t.*
from table t outer apply
     (select top (1) t1.*
      from table t1
      where t1.id < t.id
      order by t1.id desc
     ) t1
where (t.days > t1.maximumdays or t1.maximumdays is null);

【讨论】:

    【解决方案2】:

    我认为lag() 可能是最简单的方法:

    select t.*
    from (select t.*, lag(maximumdays, 1, 0) over (order by id) as prev_maximumdays
          from t
         ) t
    where days >= prev_maximumdays;
    

    在 SQL Server 2008 中,您有多种选择。假设你可以信任id,最好的是:

    select t.*
    from t left join
         t tprev
         on t.prev.id = t.id - 1
    where days >= t.prev.maximumdays;
    

    【讨论】:

    • 抱歉。 Sql server 版本为 2008 R2
    • 我认为第一个查询在 SQL Server 2014 中完美运行,但我怀疑第二个查询..
    【解决方案3】:

    在这种情况下,他似乎想要给定的天数 269 - 他想要与 MaximumDays 值最接近的行 - 在这种情况下是 30 和 365。正确吗?

    更新:

    不确定您是需要整个记录还是只需要天数和范围..这是一种方法..

    declare @tab table 
    (id int, Rate int, days int, maximumdays int)
    insert into @tab
    select 1,30, 269,30
    UNION
    select 2,35, 269,9999
    UNION
    select 3,40, 269,365
    UNION
    select 4,45, 369,330
    UNION
    select 5,50, 469,365
    
    ;With DayRange as(
    select distinct 
        Days, 
        (select max( t2.MaximumDays) from @tab t2 where t2.MaximumDays < t1.Days and t1.Days=t2.Days
        ) as Range_Start, 
        (select min(t3.MaximumDays) from @tab t3 where t3.MaximumDays > t1.Days and t1.Days=t3.Days
        ) as Range_End 
    from @tab t1)
    select t1.*
    from DayRange DR 
    inner join @tab t1 on DR.Days=t1.Days and (DR.Range_start=t1.MaximumDays OR DR.Range_End =t1.maximumdays)
    

    【讨论】:

    • 感谢您指出这一点。请注意,这些类型的 cmets 最好放在 cmets 下,而不是作为答案发布。
    • 是的,看来我需要 50 声望才能发表评论
    • 好的,那我给你10个。:)
    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多