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 ?
如何使用SQL语句获取前3个月的数据?例如,如果当前日期是01/01/2012,那么如何获取2011年12月,11月,10月的数据?
Please someone guide me.
请有人指导我。
1 个解决方案
#1
13
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.
后一版本运行速度要慢得多,因为它不能使用mydate的索引。
#1
13
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.
后一版本运行速度要慢得多,因为它不能使用mydate的索引。