[Oracle] decode 函数及其用法
http://blog.csdn.net/oscar999/article/details/18399177
前言
DECODE()函数,它将输入数值与函数中的参数列表相比较,根据输入值返回一个对应值。函数的参数列表是由若干数值及其对应结果值组成的若干序偶形式。当然,如果未能与任何一个实参序偶匹配成功,则函数也有默认的返回值。
语法结构如下:decode (expression, search_1, result_1)
decode (expression, search_1, result_1, search_2, result_2)
decode (expression, search_1, result_1, search_2, result_2, ...., search_n, result_n)
decode (expression, search_1, result_1, default)
decode (expression, search_1, result_1, search_2, result_2, default)
decode (expression, search_1, result_1, search_2, result_2, ...., search_n, result_n, default)
比较表达式和搜索字,如果匹配,返回结果;如果不匹配,返回default值;如果未定义default值,则返回空值。
实例使用
1. 创建一个学生成绩表。栏位有: 学生名, 科目名和分数
- create table student_score(
- name varchar2(30),
- subject varchar2(20),
- score number(4,1)
- );
2. 插入测试数据
- insert into student_score (name,subject,score)values('zhang san','Chinese',90);
- insert into student_score (name,subject,score)values('zhang san','Mathematics',80);
- insert into student_score (name,subject,score)values('zhang san','English',79);
3.测试一:
- select name,subject,decode(subject, 'Chinese',score,0) from student_score;
结果如下:
如果是中文课程的话, 显示分数, 其他课程分数为零。
这条SQL 看上去使用意义不大。
测试二:
- select name,sum(decode(subject, 'Chinese',score,0)) as CHINESE from student_score group by name;
统计中文课程的分数。看上去有点意义。
总体看来, decode 的使用看上去和case when 有点类似。如果只是用作以上两种状况,看上去意义不大。
- select name,sum(decode(subject, 'Chinese',score,0)) as CHINESE from student_score group by name;
- select name,score as CHINESE from student_score;
使用的两句使用后的效果一样,看上去使用decode 多此一举。
行转列-有意义的使用
往以上table 再插入一些其他学生的成绩:
- insert into student_score (name,subject,score)values('li shi','Chinese',96);
- insert into student_score (name,subject,score)values('li shi','Mathematics',86);
- insert into student_score (name,subject,score)values('li shi','English',76);
- insert into student_score (name,subject,score)values('wang wu','Chinese',92);
- insert into student_score (name,subject,score)values('wang wu','Mathematics',82);
- insert into student_score (name,subject,score)values('wang wu','English',72);
使用以下SQL:
- select name,
- sum(decode(subject, 'Chinese', nvl(score, 0), 0)) "Chinese",
- sum(decode(subject, 'Mathematics', nvl(score, 0), 0)) "Mathematics",
- sum(decode(subject, 'English', nvl(score, 0), 0)) "English"
- from student_score
- group by name;
返回:
将行的数据转化为列, 是不是很有意义了。
使用case then 也可以达到相同的效果。
- select name,
- sum(case when subject='Chinese'
- then nvl(score,0)
- else 0
- end) "Chinese",
- sum(case when subject='Mathematics'
- then nvl(score,0)
- else 0
- end) "Mathematics",
- sum(case when subject='English'
- then nvl(score,0)
- else 0
- end) "English"
- from student_score
- group by name;