如何在case条件内编写select查询?



如何在case条件下编写select查询?我正在写一个SQL语句与case语句,我可以在case内运行select查询。

如果当前时间在凌晨3点之前,则返回sysdate-1,否则返回sysdate-2。

select case when to_number(to_char(trunc(sysdate, 'hh'), 'h24')) in (00, 01, 02) then
select * from table where datetime > sysdate-1
else
select * from table where datetime > sysdate-2
end

我得到一个语法错误。有人能帮帮我吗?

使用常规的AND/OR:

select *
from table
where (to_number(to_char(trunc(sysdate, 'hh'), 'h24')) not in (00, 01, 02)
and datetime > sysdate - 2)
or datetime > sysdate - 1       -- i.e. "in (00, 01, 02)"

(大多数产品发现AND/OR比大小写表达式更容易优化)

逻辑有点颠倒了。将case移到where子句中,它将按预期工作。

select * from table 
where
datetime > sysdate - case when to_number(to_char(trunc(sysdate, 'hh'), 'h24')) in (00, 01, 02) then -1 else -2 end

最新更新