DECODE的语法:DECODE(value,if1,then1,if2,then2,if3,then3,...,else)
表示如果value 等于if1时,DECODE函数的结果返回then1,...,如果不等于任何一个if值,则返回else。
实例:
计算出1980,1981,1982三年入职的员工总人数和每年入职人数.
select count(empno) total,
count(decode(to_char(HIREDATE,'yyyy'),'1980',1,null)) "1980",
count(decode(to_char(HIREDATE,'yyyy'),'1981',1,null)) "1981",
count(decode(to_char(HIREDATE,'yyyy'),'1982',1,null)) "1982"
from emp
where to_char(HIREDATE,'yyyy') in ('1980','1981','1982')
结果:
解读sql:
这里巧妙运用decode函数和to_char函数实现单个年份人数的count计算.
首先使用to_char函数将入职年份转换成yyyy格式,然后使用decode函数进行比较运算,如果符合条件,则计算count(1),否则count(null).
注意:count(null)为0,count(1)计算实际的记录数.