结论:总体来说,有null值时对数据求和一般无影响。
- 如果在某个分组内既有null值,又有非null值时,求和时会自动把null当作0处理;
- 如果在某个分组内全是null值,求和时这个分组不会消失,且最后结果仍是null;
- 横向相加会有影响;
下面是自己上传了一些简单的测试数据,验证以上结论:
测试1: 对单个表
比如原始数据为data_test:
id | cnt |
1 | 2 |
2 | null |
2 | 7 |
3 | 3 |
4 | 5 |
对id分组求和:
select
id,
sum(cnt)
from
data_test
group by
id;
id | _c1 |
3 | 3 |
2 | 7 |
1 | 2 |
4 | 5 |
整列数据求和:
select
sum(cnt)
from
data_test
结果为17。
综上可见,在单个表有null值时,null对求和没有产生影响;
测试2:对多表连接
表1:id_test
id | cnt |
1 | 2 |
2 | 7 |
3 | 3 |
4 | 5 |
表2:id_value_test
id | cnt |
1 | 2 |
2 | 7 |
3 | 3 |
4 | 5 |
两张表左连接后的结果:
select
t1.*,
t2.cnt
from
id_test t1
left join id_value_test t2 on t1.id = t2.id;
id | cnt |
2 | 7 |
3 | 3 |
1 | 2 |
5 | null |
4 | 5 |
两张表左连接后再对id分组求和后的结果:
select
t1.id,
sum(t1.cnt)
from
(
select
t1.*,
t2.cnt
from
wjda_dev.id_test t1
left join wjda_dev.value_data_test t2 on t1.id = t2.id
) t1
group by
t1.id;
id | _c1 |
4 | 5 |
5 | null |
1 | 2 |
2 | 7 |
3 | 3 |
分组没有消失,且id为5的分组求和结果仍为null 。
横向相加会有影响:
select
*,
c1 + c2,
nvl(cast(c1 as bigint),0) + nvl(cast(c2 as bigint),0)
from
test_null;
c1 | c2 | _c1 | _c2 |
1 | null | null | 1 |
1 | 1 | 2 | 2 |
2 | 4 | 6 | 6 |
2 | null | null | 2 |