2011-11-28 112 views
4

我正在嘗試在SQL查詢中使用CASE語句,而且它並沒有像我認爲的那樣工作。使用日期的MySQL CASE語句

基本上,我有三個場景,我需要履行它使用日期字段,以便例如,我有以下數據:

id | date_activated 
1 | 2011-10-10 07:00:06 
2 | 2011-03-12 10:00:00 
3 | 2011-11-27 18:10:36 
4 | 2010-01-25 14:30:43 
5 | 0000-00-00 00:00:00 

使用下面的SQL:

select id, 
case date_activated 
when date_activated > '2011-11-23 18:30:00' then 'after' 
when date_activated > '2010-01-20 00:00:00' then 'before' 
else 'not yet' 
end as date_note 
from table1 

應攜帶out:

id | date_activated  | date_note 
1 | 2011-10-10 07:00:06 | before 
2 | 2011-03-12 10:00:00 | before 
3 | 2011-11-27 18:10:36 | after 
4 | 2010-01-25 14:30:43 | before 
5 | 0000-00-00 00:00:00 | not yet 

但是,這是拉出來的:

id | date_activated  | date_note 
1 | 2011-10-10 07:00:06 | not yet 
2 | 2011-03-12 10:00:00 | not yet 
3 | 2011-11-27 18:10:36 | not yet 
4 | 2010-01-25 14:30:43 | not yet 
5 | 0000-00-00 00:00:00 | after 

我不明白我在做什麼錯,但我敢打賭這是簡單的事情!誰能幫助嗎?

+1

是'date_activated'一個實際的日期時間字段,或者它是char/varchar? –

+0

這是一個實際的日期時間字段 –

回答

10

嘗試這一個 -

SELECT 
    id, 
    CASE 
    WHEN date_activated > '2011-11-23 18:30:00' THEN 'after' 
    WHEN date_activated > '2010-01-20 00:00:00' THEN 'before' 
    ELSE 'not yet' 
    END AS date_note 
FROM table1; 

有MySQL的兩個案例流量的功能,你應該使用一個與條件。

+0

它的工作原理,謝謝!我無法相信這是我需要做的 - 只是在案件開始後刪除域名! –