如一张表定义如下:
create table Score(
id char(24),
english number(3,1);
math number(3,1);
);
里面的记录如下:
1 89 null
2 null 90
想要查询全部学生的英语成绩,sql语句如下
select sum(nvl(english,0))
from Score;
现在如果有另外一个Score1表,他的定义和Score一样,
里面的数据为:
1 null 90
3 90 null
要查询这两个表里id为1的英语成绩之和
Sql:
select sum(nvl(a.english,0))+sum()
from Score a ,Score b
where a.id='1' and b.id='1';
这样写,是用相当大的问题,不一定会有正确的结果。
能有正确的结果的sql是:
select (
select sum(nvl(english,0))
from Score where id=1
)
+
(
select sum(nvl(english,0))
from Score1 where id=1
)
from dual;
但是这样还有个问题,如果查的id为2,Score1中没有这条记录,所以
(
select sum(nvl(english,0))
from Score1 where id=2
)
返回的还是空,应该在外面在添加nvl,把它转化为0。