【问题标题】:CASE or IF condition in WHERE clause for the below requirement以下要求的 WHERE 子句中的 CASE 或 IF 条件
【发布时间】:2019-03-16 04:15:52
【问题描述】:

我有以下要求,但我不知道如何编写 Oracle SQL 查询以根据给定条件获取数据。

要求:

人员表

Name       created_date   updated_date
-------    -----------    ------------
Alex       11-oct-2018     
John       10-oct-2018    11-oct-2018

我想根据 UI 上给出的 from 和 to date 来获取记录名称 created_date 或 updated_date 作为 last_modified_date,如果 updated_date 不为 null,它应该在 fromdate 和 todate 之间的 updated_date 上搜索 updated_date。如果updated_date 为null,那么它应该在fromdate 和todate 之间搜索created_date,如created_date。

我这样试过,有编译问题,我不怎么写

select name,
       case when update_date is null then created_date else updated_date as last_modified_date 
from Person 
where case when updated_date is null 
           then trunc(created_date) between fromdate and todate 
           else trunc(updated_date) between fromdate and todate.'

【问题讨论】:

  • 通常最好在 WHERE 子句中使用 AND/OR 结构,而不是 case/coalesce 等。
  • 你能提供样本输出吗??
  • 非常感谢您的帮助。
  • 这里列出的所有答案都很完美。感谢您的帮助。

标签: sql oracle case


【解决方案1】:

您在 where 子句上写正确的 sql 语法是错误的,如下所示

    select name, 
           case when update_date is null 
           then created_date else 
           updated_date end as last_modified_date 
    from Person
    where case when updated_date 
    is null then trunc(created_date)
      else 
    trunc(updated_date) end
    between fromdate and todate

通过使用COALESCE 函数,您可以进行相同的比较

select name,COALESCE(update_date,created_date)
from Person
where COALESCE(update_date,created_date) between fromdate and todate

你的错误区域

    case when updated_date 
    is null then trunc(created_date) between fromdate and todate --here between is wrong sql syntax (condition)
   else 
    trunc(updated_date) between fromdate and todate --(same thing you did for else)

【讨论】:

  • 以上两个答案都很完美。谢谢哈里。
【解决方案2】:

使用:

CASE WHEN [条件] THEN [return_expr] ELSE [else_expr] END

Select name, 
       CASE WHEN update_date IS NULL
            THEN created_date
            ELSE updated_date END AS last_modified_date
  FROM Person
 WHERE CASE WHEN updated_date IS NULL
            THEN TRUNC(created_date)
            ELSE TRUNC(updated_date) END BETWEEN fromdate AND todate;

或仅用于 oracle:

NVL([expr1], [expr2])

Select name, 
       NVL(update_date, created_date) AS last_modified_date
  FROM Person
 WHERE NVL(updated_date, created_date) BETWEEN fromdate AND todate;

【讨论】:

  • 我建议使用 COALESCE([EXPR1],[EXPR2],...[EXPRN]) 而不是 NVL,因为它是 SQL92 标准,更强大(它需要任意数量的参数)并且不像 NVL 那样特定于供应商
  • 上述两个查询都运行良好。非常感谢。哈里
【解决方案3】:

这样的?

select name, nvl(update_date,created_date) as last_modified_date
from Person 
where nvl(update_date,created_date) between fromdate and todate;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多