Pergunta

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)  
Foi útil?

Solução

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.

Outras dicas

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top