例如:n1 和 n2,想知道任何 oracle 内置函数都可以实现吗?
样本条件和预期输出:
- 如果 n1 为 null 且 n2 为 null,则返回 null
- 如果 n1 为空且 n2 不为空,则返回 n2
- 如果 n1 不为空且 n2 为空,则返回 n1
- 如果 n1 和 n2 不为空,则返回 n1 和 n2 的总和
检查这个:
case when n1 is not null and n2 is not null then
n1 + n2
else
COALESCE(n1,n2)
end
带单coalesce
COALESCE(n1+n2,n1,n2)
create table t as select 1 n1, 2 n2 from dual union all select null, 2 from dual union all select 1, null from dual union all select null, null from dual
4 行受影响
select COALESCE(n1+n2,n1,n2) from t
| 聚结(N1+N2,N1,N2) | | --------------------: | | 3 | | 2 | | 1 | | 空|
db<>在这里摆弄
你可以试试下面的 -
with data as (
select 1 X, 2 Y, 1 sno from dual
union
select null X, 2 Y, 2 sno from dual
union
select 1 X, null Y, 3 sno from dual
union
select null X, null Y, 4 sno from dual
)
select sno, X, Y, coalesce(X+Y,X,Y) from data
order by sno
+-----+--------+--------+-------------------+
| SNO | X | Y | COALESCE(X+Y,X,Y) |
+-----+--------+--------+-------------------+
| 1 | 1 | 2 | 3 |
| 2 | (null) | 2 | 2 |
| 3 | 1 | (null) | 1 |
| 4 | (null) | (null) | (null) |
+-----+--------+--------+-------------------+
这可以使用 CASE 表达式和 coalesce() 的组合来完成:
case
when n1 is null and n2 is null then null
else coalesce(n1, 0) + coalesce(n2, 0)
end as n1_n2_sum