I have a table that contains only Month and Year field both as int.
Given an input say month, 6 months.
I need to project the data that are 6 months old.
for example I have data from 2001 , 1st Janaury till date. Given input as 6 months , so I have to go back 6 months
from cuurent date to get the result .
Output will be Data From Jan 2001 to Jan 2012.
I have done the program using the right,substring, string comparison.(a nasty hack)
Is there any prominent way of doing so?
DDL
Declare @t table (Mnth int, Yr int)
Insert Into @t
-- 2011
Select 1,2011 Union All select 2,2011 Union All Select 3, 2011 Union ALL Select 4,2011 Union ALL
Select 5,2011 Union All select 6,2011 Union All Select 7, 2011 Union ALL Select 8,2011 Union ALL
Select 9,2011 Union All select 10,2011 Union All Select 11, 2011 Union ALL Select 12,2011 Union ALL
--2012
Select 1,2012 Union All select 2,2012 Union All Select 3, 2012 Union ALL Select 4,2012 Union ALL
Select 5,2012 Union All select 6,2012 Union All Select 7, 2012 Union ALL Select 8,2012 Union ALL
Select 9,2012 Union All select 10,2012 Union All Select 11, 2012 Union ALL Select 12,2012
Declare @inputMonth int = 6
I am trying without string conversion
Select Mnth,Yr,YEAR(DATEADD(mm,-@inputMonth,getdate())),MONTH(DATEADD(mm,-@inputMonth,getdate()))
From @t
WHERE YEAR(DATEADD(mm,-@inputMonth,getdate())) < Yr
AND MONTH(DATEADD(mm,-@inputMonth,getdate())) < Mnth
But it is not working
Thanks
You could always convert to datetime and compare that.
Something like:
i.e. concatenate your two columns to yield
CONVERT(Datetime, "2011-1-01"), for instance.As this answer to another question points out, ify ou don’t want to do string conversions, you would have to add to do a series of
DATEADDto0, which is1900-01-01.