Home Forums SQL Server 2008 T-SQL (SS2K8) pulling records from a table between date ranges in another table RE: pulling records from a table between date ranges in another table

  • If i got it right ...

    Suppose there's date range lookup table with N dates

    create table #RangeLookup (

    dt date

    )

    declare @strtDate date = '20140101'

    declare @step int = 30

    declare @N int = 20

    insert #RangeLookup

    select top (@N) dateadd(dd, @step*(row_number() over (order by (select null))-1), @strtDate)

    from sys.all_columns

    Step is not supposed to be always fixed as it is in the above example.

    Now one can build a view or cte kind of

    ;with c1 as (

    select dt, rn= row_number() over (order by dt)

    from #RangeLookup

    ),

    RangeLookup2 as ( -- N-1 intervals with tags

    select dStart = a.dt

    , dEnd = dateadd (dd, -1, b.dt)

    , tag = datediff (dd, (select top 1 dt from #RangeLookup order by dt), b.dt)

    from c1 a

    join c1 b on a.rn= b.rn-1

    )

    select * from RangeLookup2

    Then just compare myDate in question against interval to get the tag.

    Rgds

    Serg