Extracting specific data range

  • How can i extract last 12 months from the given dates? 
    I can get the desire result if I give a specific value to@filter and minus off the year. But how to achieve the correct result, suppose,if @filter is GETDATE().
    This one is giving me wrong answer.:Declare @filter date = GETDATE()select TheMonth from DataRangewhere yEAR(TheMonth) <=YEAR(GETDATE())-1 and year(TheMonth)>year(GETDATE())-2
    This gives me the correct answer when I use hardcoded value :Declare @filter date = '2017-07-01'select TheMonth from ByDeptByMonthwhere TheMonth <='2016-07-01' and TheMonth>'2015-07-01'

  • Take a look at the DATEADD() function.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Thanks I get it.
    Declare @filter date = GETDATE()select TheMonth from DataRangewhere TheMonth<=dateadd(year,-1,GETDATE()) and TheMonth>dateadd(year,-2,GETDATE())

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply