Question

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)  
Was it helpful?

Solution

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top