获取范围值
Getting the Range Value
我有以下 table 来自查询
我想使用 MaxmiumDays 列获得适合上述 269 范围的最佳范围列表。请检查以下输出。
我认为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;
对于旧版本,您可以使用 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);
在这种情况下,他似乎想要给定的天数 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)
我有以下 table 来自查询
我想使用 MaxmiumDays 列获得适合上述 269 范围的最佳范围列表。请检查以下输出。
我认为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;
对于旧版本,您可以使用 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);
在这种情况下,他似乎想要给定的天数 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)