with temp as(
select100 d1,to_date('20170901','yyyyMMdd') d2 from dual
unionallselect100 d1,to_date('20171001','yyyyMMdd') d2 from dual
unionallselect100 d1,to_date('20171101','yyyyMMdd') d2 from dual
unionallselect100 d1,to_date('20171201','yyyyMMdd') d2 from dual
unionallselect100 d1,to_date('20180101','yyyyMMdd') d2 from dual
unionallselect100 d1,to_date('20180201','yyyyMMdd') d2 from dual
)
selectavg(d1) avg_d1,
avg(casewhen d2>=to_date('20171201','yyyyMMdd') then d1 else0end) avg_error,--错误
avg(casewhen d2>=to_date('20171201','yyyyMMdd') then d1 elsenullend) avg_three--对的
from temp;
结果
d1
avg_error
avg_three
100
50
100
解释:oracle在计算平均值时,不会统计null值。所以,不符合条件时置为null。
2、!= 。not like 过滤掉空值
with temp as(
select100 d1,'2018' d2 from dual
unionallselect100 d1,'2016' d2 from dual
unionallselect100 d1,'2017' d2 from dual
unionallselect100 d1,'2018' d2 from dual
unionallselect100 d1,null d2 from dual
unionallselect100 d1,null d2 from dual
)
select d1,
d2
from temp
where d2!='2018';--运用了!= ,该处使用not like '2018'结果将一致
结果:null值不见了,是不是感觉到很疑惑
d1
d2
100
2016
100
2017
解释: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 isnull;