steven
steven

Reputation: 393

Select data for last X month from table with year and month separated in different coloumns

on my SQL Server I have a table with a lot of data. There are two columns for year (smallint) and month (tinyint).

What is the best and most performed way to separate data for the last X month.

I have declared variables

with correct values. Now I have realised that my WHERE statement doesn't work as expected:

WHERE (year >= @yearfrom AND month >= @monthfrom) 
AND (year <= @yearto AND month <= @monthto)

Because when selecting the data from the last 12 month, my variables are

and the SELECT would just give me data from 09 2012/2013

WHERE (year >= 2012 AND month >= 9) 
AND (year <= 2013 AND month <= 9)

So, actually there are two possiblities to solve the problem:

Any suggestion how to solve this problem?!?!?

Thanks for every reply...

Upvotes: 2

Views: 681

Answers (1)

t-clausen.dk
t-clausen.dk

Reputation: 44326

WHERE (year = @yearfrom AND month >= @monthfrom or year > @yearfrom) 
AND (year = @yearto AND month <= @monthto or year < @yearto)

Upvotes: 1

Related Questions