我正在尝试在我拥有的 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 流函数,您应该使用一个带条件的。
关于使用日期的 MySQL CASE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8297488/