Search code examples
sqlsql-servert-sqlsql-server-2014

SQL Server: get all previous values that are within half year of a month (not in future)?


I have values such as

201401
201411
201501
201504
201508
201606

If I select values last six months from 201501, I want to get 201411. If last six months from 201606, then nothing. If from 201508, then 201504.

I have a month column of the varchar form 201601.

How can I get the last six months relative to each month with some datatype objects such as datepart functions?


Solution

  • Another option which will reduce record level processing/conversions

    Declare @YourTable table (SomeCol varchar(6))
    Insert Into @YourTable values
    (201401),
    (201411),
    (201501),
    (201504),
    (201508),
    (201606)
    
    Declare @Target varchar(6) = '201508'
    
    Select *
     From  @YourTable
     Where SomeCol >= format(dateadd(MONTH,-6,cast(@Target+'01' as date)),'yyyyMM') 
       and SomeCol < @Target
    

    Returns

    201504