oracle:解码和子查询选择结果
我有一个 Oracle 查询,其中一部分是使用 DECODE 计算一些值。例如:
SELECT ...,
(SELECT DECODE((SELECT 23 FROM DUAL),
0, null,
(SELECT 23 FROM DUAL))
FROM DUAL)
FROM ...
这里的值“23”是在运行时计算的,并且它是相当复杂的连接 - 多个表,使用 PARTITION BY 等。因此,如果该值不是“,我想避免执行相同的子查询” 0”。有没有办法写这样的东西
SELECT ...,
(SELECT DECODE ((SELECT 23 FROM DUAL) as test,
0, null,
test)
FROM DUAL)
FROM ...
I have a oracle query and part of it is calculating some value using DECODE. For example:
SELECT ...,
(SELECT DECODE((SELECT 23 FROM DUAL),
0, null,
(SELECT 23 FROM DUAL))
FROM DUAL)
FROM ...
Here the value "23" gets calculated at runtime, and it's quite complicated joins - multiple tables, uses PARTITION BY
etc. So I want to avoid executing the same subquery if the value is not "0". Is there any way to write something like this
SELECT ...,
(SELECT DECODE ((SELECT 23 FROM DUAL) as test,
0, null,
test)
FROM DUAL)
FROM ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这对你有用吗?
我刚刚将“23”移动到带有描述性别名的内联表中。
CASE 语句也可能会增加清晰度,如下所示:
Will this work for you?
I've just moved the "23" to an inline table with a descriptive alias.
A CASE statement might also add clarity, as in:
或者:
允许您在整个主选择中使用查询“q”(只要允许子查询)。称为WITH 子句、公共表表达式或子查询分解。请访问 Oracle-Base.com 了解更多相关信息。
Or:
Lets you use the query "q" throughout your main select, where ever a subquery is allowed. Called the WITH clause, or Common Table Expression, or Subquery Factoring. Read more about it at Oracle-Base.com.
对于此特定场景,您可以使用
NULLIF
函数:如果两个参数相等,
NULLIF
函数将返回NULL
,否则返回第一个参数。For this particular scenario, you could use the
NULLIF
function:The
NULLIF
function returnsNULL
if the two arguments are equal, otherwise it returns the first argument.您可以在 from 子句中使用子查询并执行如下操作:
You can use the subquery in from clause and do something like below:
最好使用 CASE 语句。因为 CASE 语句就像一系列 IF 语句,仅使用关键字 WHEN。 CASE 语句是从上到下评估的。如果条件为真,则执行相应的 THEN 子句,并跳转到 END CASE(短路评估)子句。
Better you would have use CASE statement. since the CASE statement is like a series of IF statements, only using the key word WHEN. A CASE statement is evaluated from top to bottom. If a condition is true, then corresponding THEN clause is executed and execution jumps to the END CASE (short circuit evaluation) clause.