Tuesday, November 2, 2010

Previous Month Query

We always encounter this issue, how to query previous month data in sql statement
and as always we will get an easy idea, just subtract 1 from current date

example :

month(curdate())- 1

yes this is one easy way to do it, but we will encounter 1 big problem with this statement,current date month is January 2010 and the statement result for the previous month will be 0, that means your query will query month = 0 and your query will give you a null result

solution :
use interval in your query

month(curdate() - interval 1 month)
by using interval the query result is 12 when the current date month is January

this solution also apply to previous year
year(curdate() - interval 1 year)

interval unit available is
FRAC_SECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR

this is just the basic of it, how to implement it to your query its up to you
but hey this is just my opinion, if there is any other better way please respond in comment area ^^

No comments:

Post a Comment