如何计算NULL
值?
例如:
select sum(nvl(a,0) + nvl(b,0)) s, c from
(
select 1 a, null b, 'A' c from dual union
select null, null b , 'c' c from dual
)
group by c
预期结果:当a
为NULL
时,b
为NULL
,则sum(nvl(a,0) + nvl(b,0))
为NULL
。我怎么能这样做?
答案 0 :(得分:4)
使用CASE
语句检测A
和B
何时NULL
:
Oracle 11g R2架构设置:
CREATE TABLE sample_data ( a, b, c ) AS
SELECT 1, CAST( NULL AS NUMBER ), 'A' FROM DUAL UNION ALL
SELECT NULL, NULL, 'C' FROM DUAL
查询1 :
SELECT SUM(
CASE
WHEN a IS NULL AND b IS NULL
THEN NULL
ELSE nvl(a,0) + nvl(b,0)
END
) AS s,
c
FROM sample_data
GROUP BY c
<强> Results 强>:
| S | C |
|--------|---|
| 1 | A |
| (null) | C |
答案 1 :(得分:1)
您可以尝试:
select Case when (sum(nvl(a,0) + nvl(b,0))) = 0 then null
else sum(nvl(a,0) + nvl(b,0)) end s, c
from
(
select 1 a, null b, 'A' c from dual union
select null, null b , 'c' c from dual
)
group by c