How would I go about retrieving records from the last three months of the previous year? I was thinking it would be:

 Date_add(curdate() , interval '-1 2' year_month)  
有帮助吗?

解决方案

Try this:

WHERE my_date_column BETWEEN
  SUBDATE(CURDATE(), INTERVAL DAYOFYEAR(CURDATE()) + 91 DAY) AND
  SUBDATE(CURDATE(), INTERVAL DAYOFYEAR(CURDATE()) DAY)

91 is one less than 31 + 30 + 31, because BETWEEN is inclusive.

Note that if your column is a datetime type, you'll need the end value to be the last second of the day:

SUBDATE(SUBDATE(CURDATE(), INTERVAL DAYOFYEAR(CURDATE()) - 1 DAY), INTERVAL 1 SECOND)

See SQLFiddle of these expressions generating correct values.

其他提示

Assuming you date column is named "date", something like:

SELECT 
*
FROM 
table

WHERE
YEAR(date) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))

AND
MONTH(date) BETWEEN 10 AND 12
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top