【问题标题】:Setting Condition in Case Statement在 case 语句中设置条件
【发布时间】:2019-06-07 07:38:32
【问题描述】:

假设有这样的表结构

Name | Class | CS_ex_date | IT_ex_date|

xyz  | CSE   | 10 june    |  Null     |
123  | ECE   | Null       |  Null     |
456  | MECH  | Null       |  Null     |
678  | MECH  | Null       |  Null     |
abc  | IT    | Null       | 3 Aug     |

我想使用 case 语句创建一个 select 语句,case 语句中有一些条件。

我已经在 where 条件中看到了 case 语句和 case 语句的常用语法,但我想在 THEN 部分中添加一些条件。我的语法有问题,找不到任何可以参考的例子。

我的查询是这样的:

select * 
  from student 
 where (case 
          when class like '%SE%' 
            then CS_ex_date > sysdate and CS_ex_date < sysdate + 60
          when class like '%T%' 
            then IT_ex_date > sysdate and IT_ex_date < sysdate + 60 
        end);

我不确定查询的语法并得到 ORA-00905: missing keyword。

预期的输出应该是

Name | Class | CS_ex_date | IT_ex_date|

xyz  | CSE   | 10 june    |  Null    |
abc  | IT    | Null       | 3 Aug    |

有没有办法解决这个问题。使用任何其他方法都会产生相同的结果。

【问题讨论】:

  • 它实际上是一个case 表达式。这不是一个微不足道的区别:一个表达式返回一个单一的原子值。这意味着它不能以这种方式用于程序流。

标签: sql oracle


【解决方案1】:

您似乎想要or,而不是case

select * 
  from student 
 where (class like '%SE%' and CS_ex_date > sysdate and CS_ex_date < sysdate + 60) or
       (class like '%T%'  and IT_ex_date > sysdate and IT_ex_date < sysdate + 60)

【讨论】:

  • 感谢@Dmitry Bychenko 给出的结果。
【解决方案2】:

您可以使用CASE 语句在子查询中计算与谓词相关的值,然后在WHERE 条件中使用它:

with student_dt as
(select 
   student.*,
   case 
          when class like '%SE%' 
            then CS_ex_date  
          when class like '%T%' 
            then IT_ex_date  
        end as check_date
  from student)
select * from  student_dt 
 where check_date > sysdate and check_date < sysdate + 60; 

这使得查询更加冗长,但保留了可能在谓词转换中丢失的意图。

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多