答案 0 :(得分:3)
对于旧版本,您可以使用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);
答案 1 :(得分: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;
答案 2 :(得分:1)
在这种情况下,他想要给定的天数为269-在这种情况下,他希望具有与MaximumDays最接近的值的行-在这种情况下,为30和365。这是正确的吗?
更新:
不确定是需要全部记录还是仅需要Days and Range ..这是完成记录的一种方法。
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)