TechGuy
TechGuy

Reputation: 4570

Get Data Last Year From This Month SQL

I have a year & month in my database tables seperate column.(like Year 2017 , Month 8) I need to filter that data for I need past year data from today. I want 13 months of data to be returned.

If today is 13/8/2018 and i need data From 8/2017 to 8/2018 only.

I tried it like this,

SELECT Year,Month,News
FROM TBL_NEWS
WHERE Year >= cast(datepart(yyyy,DATEADD(yyyy,-1,getdate()))

Upvotes: 0

Views: 90

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270883

You have split the date into two columns. That can be tricky. Here is one method for 12 months of data:

where datefromparts(year, month, 1) >= datefromparts(year(getdate()) - 1, month(getdate()), 1) and
      datefromparts(year, month, 1) < datefromparts(year(getdate()), month(getdate()), 1)

If you actually want 13 months of data, change the < to <=.

Upvotes: 2

Related Questions