Teej
Teej

Reputation: 12873

Retrieve Date based on Month in MySQL

I am trying to select a year value depending on the month the record was created:

If the month is January onwards, I should get last year If the month is April onwards, I should get this year

SELECT IF ((MONTH(Application.created) > 3), (YEAR(Application.created)), (YEAR(Application.created, INTERVAL -1 YEAR))) FROM Table

Upvotes: 1

Views: 60

Answers (1)

Ed Gibbs
Ed Gibbs

Reputation: 26333

You can just subtract 1 (no interval required) from the year value. Also, I used CASE because I was getting lost in all the parentheses :)

SELECT
  CASE WHEN MONTH(Application.created) > 3 THEN YEAR(Application.created)
       ELSE YEAR(Application.created) - 1
  END
FROM Table

Edit:

SELECT IF ((MONTH(Application.created) > 3), (YEAR(Application.created)), (YEAR(Application.created) - 1)) FROM Table

Upvotes: 2

Related Questions