在MySQL中根据月份检索日期

时间:2013-05-21 13:34:54

标签: mysql

我正在尝试根据创建记录的月份选择年份值:

如果月份是1月份,我应该去年 如果这个月是4月以后,我今年应该得到

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

1 个答案:

答案 0 :(得分:2)

您可以从年份值中减去1(不需要interval)。另外,我使用CASE因为我在所有括号中迷路了:))

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

编辑:

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