MySQL CASE语句使用日期

我正在尝试在我的SQL查询中使用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

应该带出:

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

我无法理解我做错了什么,但我敢打赌它很简单!
最佳答案
试试这个 –

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中有两个CASE流函数,你应该使用一个条件.

相关文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注