2013-05-21 56 views
1

我想請根據所記錄的創建月份年份值:檢索基於月日在MySQL

如果月份是1月起,我應該得到去年 如果月份爲4月起,我應該在今年得到

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

回答

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 
+0

我居然陷進去了'IF'語句,但你給我的只是減去想法' 1' –

+0

我加了實際的'IF' –

+1

沒問題!謝謝 - 擁有IF版本可以改善答案。 –