我有一个以下要求,但我不知道如何编写Oracle SQL查询以根据给定条件获取数据。
要求:
人员表
Name created_date updated_date
------- ----------- ------------
Alex 11-oct-2018
John 10-oct-2018 11-oct-2018
我想基于UI上给出的起始和日期来获取记录名称,created_date或updated_date作为last_modified_date,并且如果updated_date不为null,它应该搜索fromdate和todate之间的updated_date,例如updateddate。如果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.'
答案 0 :(得分:3)
像这样吗?
select name, nvl(update_date,created_date) as last_modified_date
from Person
where nvl(update_date,created_date) between fromdate and todate;
答案 1 :(得分:0)
您在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 :(得分:0)
使用:
在[条件]然后[return_expr] ELSE [else_expr]结束时的情况
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;