使用日期的 MySQL CASE 语句

标签 mysql sql 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 流函数,您应该使用一个带条件的。

关于使用日期的 MySQL CASE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8297488/

相关文章:

asp.net - MySql 音频库

SQL JOIN 在第一个结果后忽略其他列

sql - 是否有 Postgres 特性或内置函数将 uuid 的显示限制为仅使它们具有唯一可识别性?

mysql - SQL SELECT CASE 与 SELECT

sql - 具有 NULL 值的 CASE 表达式

php - 如何在Mysql中将Top Value字段显示为top

mysql - SQL 派生表

java - 将csv文件导入MySQL数据库时出现无效的utf8字符串

java - 如何将 postgresql 查询编写为 Spring-data jpa 查询

Clojure `case` 不区分不同的符号