Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous 3 months data based on current date - MySQL

Tags:

sql

mysql

How do I get the previous 3 months data using SQL statement? for example if the current date is 01/01/2012, so how to get the data for December, November, October 2011 ?

Please someone guide me.

like image 793
softboxkid Avatar asked Sep 21 '11 10:09

softboxkid


1 Answers

SELECT * FROM table1 
WHERE mydate BETWEEN DATE_SUB(now(), INTERVAL 3 MONTH) AND now()

Or if you want to stay within the months

SELECT * FROM table1 
WHERE MONTH(mydate) BETWEEN MONTH(DATE_SUB(now(), INTERVAL 3 MONTH)) AND MONTH(now())
  AND YEAR(mydate) BETWEEN YEAR(DATE_SUB(now(), INTERVAL 3 MONTH)) AND YEAR(now())

This latter version will run much slower, because it cannot use an index for mydate however.

like image 157
Johan Avatar answered Sep 17 '22 18:09

Johan