您的位置:首页 > 数据库 > Oracle

Oracle的莫名奇妙错误ORA-01403等错误

2018-02-09 10:30 465 查看

1、case when 用于avg

需求:获得总体的平均值和最后三个月的平均值

with temp as(
select 100 d1,to_date('20170901','yyyyMMdd') d2 from dual
union all
select 100 d1,to_date('20171001','yyyyMMdd') d2 from dual
union all
select 100 d1,to_date('20171101','yyyyMMdd') d2 from dual
union all
select 100 d1,to_date('20171201','yyyyMMdd') d2 from dual
union all
select 100 d1,to_date('20180101','yyyyMMdd') d2 from dual
union all
select 100 d1,to_date('20180201','yyyyMMdd') d2 from dual
)
select avg(d1) avg_d1,
avg(case when d2>=to_date('20171201','yyyyMMdd') then d1 else 0 end) avg_error,--错误
avg(case when d2>=to_date('20171201','yyyyMMdd') then d1 else null end) avg_three--对的
from temp;


结果

d1avg_erroravg_three
10050100
解释:oracle在计算平均值时,不会统计null值。所以,不符合条件时置为null。

2、!= 。not like 过滤掉空值

with temp as(
select 100
4000
d1,'2018' d2 from dual
union all
select 100 d1,'2016' d2 from dual
union all
select 100 d1,'2017' d2 from dual
union all
select 100 d1,'2018' d2 from dual
union all
select 100 d1,null d2 from dual
union all
select 100 d1,null d2 from dual
)
select d1,
d2
from temp
where d2!='2018';--运用了!= ,该处使用not like '2018'结果将一致


结果:null值不见了,是不是感觉到很疑惑

d1d2
1002016
1002017
解释:Oralce 在计算比较值时(<>,!=,not like )会自动忽略null,相当于 <列名>is not null

解决:

select d1,
d2
from temp
where nvl(d2,'0000')!='2018';--将null替换
--第二种
select d1,
d2
from temp
where d2!='2018' or d2 is null;


结果:

d1d2
1002016
1002017
100
100

3、select into 没有数据 ORA-01403

表table1数据如下:

c1c2
1002016
1002017
1002015
1002014
代码块如下:

declare
v_d1 varchar2(32);
begin
select c1 into v_d1 from where c2='8888';--没有任务记录
bdms_output.put_line(v_d1);
end;


错误 ORA-01403:not found data/未找到任何数据

解决

加上聚合函数,好处:

1、多条记录返回时不会报错

2、为null值不会替换

select max(c1) into v_d1 from where c2='8888';--没有任务记录


解释:Oracle聚合函数底层可能在没有值时将数据替换为null。

为了保险起见,select into 最好加上聚合函数,或者在使用之前if判断记录数是否为1,即大于0。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: