sumvalue和addition如何null

时间:2017-10-11 09:21:27

标签: oracle

如何计算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

预期结果:当aNULL时,bNULL,则sum(nvl(a,0) + nvl(b,0))NULL。我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

使用CASE语句检测AB何时NULL

SQL Fiddle

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