含义解释:
decode(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)
case语法一
case 条件 when 值1 then 翻译值1
when 值2 then 翻译值2
…
Else 缺省值 end
Case语法二
case when 条件1 then 翻译值1
when 条件2 then 翻译值2
…
Else缺省值 end
举两个简单的例子,简单对比一下这两者的区别:
1.CASE语句:
SELECT CASE SIGN(5 - 5)
WHEN 1 THEN 'Is Positive'
WHEN -1 THEN 'Is Negative'
ELSE 'Is Zero' END
FROM DUAL;
后台实现:
if (SIGN(5 – 5) = 1) { 'Is Positive'; }
else if (SIGN(5 – 5) = 2 ) { 'Is Negative'; }
else { ‘Is Zero’}
2. Decode函数:
SELECT DECODE(SIGN(5 – 5), 1, 'Is Positive', -1, 'Is Negative', ‘Is Zero’) FROM DUAL
后台实现:
switch ( SIGN(5 – 5) ) {
case 1 : 'Is Positive'; break;
case 2 : 'Is Negative'; break;
default : ‘Is Zero’
}
两者在比较条件是固定值时效果一样,当比较条件不固定(比较条件包含表达式)时,case when使用起来灵活方便。
其实,decode和case when很多时候是可以等效的,选用那个,完全可以由程序员自己的习惯和熟练程度来决定。但值得一提的是注意CaseWhen的两种形态,将三者罗列如下。我想最好的分析方法就是去实际写一个sql测试一下了,这儿就不多说了。
CASE expr WHENcomparison_expr1 THEN return_expr1
[WHEN comparison_expr2THEN return_expr2
WHENcomparison_exprn THEN return_exprn
ELSE else_expr]
END
(case when的一个变种)
CASE
WHEN comparison_expr1 THEN return_expr1
[WHENcomparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END
DECODE(col|expression, search1, result1 [, search2, result2,...,] [,searchn, resultn,...,] [, default])
oracle中自连接与case when,decode使用实例
有表如下:
sql@kokooa>select* from test026;
IDNAME SUBJECT SCORE
------------------------------ -------------------- ----------
1jim 语文 88
1jim 数学 84
1jim 英语 90
2kate 语文 86
2kate 数学 76
2kate 英语 96
想得到如下效果:
学生编号 学生姓名 语文数学 英语
方法:
1.自连接:(这是自连接很典型的用处应当熟练掌握)
sql@kokooa> select a.id,a.name,a.score as "语文",b.score as "数学",c.score as "英语"
2 from test026 a,test026 b,test026 c
3 where a.id=b.id and a.subject='语文' and b.subject='数学'
4 and a.id=c.id and c.subject='英语';
ID NAME 语文 数学 英语
---------- -------------------- ---------- ---------- ----------
1 jim 88 84 90
2 kate 86 76 96
2 使用case when
sql@kokooa>select id,name,
2 sum(case when subject='语文' then score end) as "语文",
3 sum(case when subject='数学' then score end) as "数学",
4 sum(case when subject='英语' then score end) as "英语"
5 from test026
6 group by id,name
7 /
ID NAME 语文 数学 英语
---------- -------------------- ---------- ---------- ----------
1 jim 88 84 90
2 kate 86 76 96
3 decode
1 select max(id) as id,name,
2 max(decode(subject,'数学',score)) as "数学",
3 max(decode(subject,'语文',score)) as "语文",
4 max(decode(subject,'英语',score)) as "英语"
5 from test026
6* group by name
sql@kokooa>/
ID NAME 数学 语文 英语
---------- -------------------- ---------- ---------- ----------
1 jim 84 88 90
2 kate 76 86 96