2011-11-28 70 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

它的工作原理,谢谢!我无法相信这是我需要做的 - 只是在案件开始后删除域名! –