首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在case条件下编写选择查询?

如何在case条件下编写选择查询?
EN

Stack Overflow用户
提问于 2022-06-09 11:10:05
回答 2查看 63关注 0票数 0

如何在case条件下编写选择查询?我正在用case语句编写SQL语句,在其中我可以在case中运行select查询。

如果当前时间是凌晨3点之前,下面的查询将返回sysdate-1的条目,否则返回sysdate-2的条目。

代码语言:javascript
复制
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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-06-09 12:08:28

使用常规的AND/OR代替:

代码语言:javascript
复制
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)"

(大多数产品发现和/或比case表达式更容易优化。)

票数 1
EN

Stack Overflow用户

发布于 2022-06-09 12:08:21

你的逻辑有点颠倒。将大小写移到where子句中,它将按预期工作。

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72559266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档