user2838928
user2838928

Reputation: 57

MySQL get records between now and a month last year

I am trying to create an SQL query to select records where the timestamp is less than NOW() but is greater than september last year, but i dont want to specify the year by putting something like:

date > '01/09/2014'

If i were to run the query today it should give me records from:

september 2014 to May 2015 (May as it is the month at the time of creating this question)

If i run it next year it should give me records from september 2015 to May 2016 (May as it is the month at the time of creating this question)

Upvotes: 0

Views: 613

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269443

You can construct the date:

where date >= str_to_date(concat(year(now()) - 1, '-09-01'),
                          '%Y-%m-%d') and
      date < now()

I am guessing that you actually want a slightly more complicated condition. If you run the query at the end of the year (say in December), you probably want September of the current year:

where date >= str_to_date(concat(year(now()) - (month(now) < 9), '-09-01'),
                          '%Y-%m-%d') and
      date < now()

Upvotes: 5

Related Questions