oracle中的decode的使用
来源:互联网 发布:qq游戏网络加速器 编辑:程序博客网 时间:2024/05/18 03:03
含义解释:
decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值)
该函数的含义如下:
IF 条件=值1 THEN
RETURN(翻译值1)
ELSIF 条件=值2 THEN
RETURN(翻译值2)
......
ELSIF 条件=值n THEN
RETURN(翻译值n)
ELSE
RETURN(缺省值)
END IF
decode(字段或字段的运算,值1,值2,值3)
这个函数运行的结果是,当字段或字段的运算的值等于值1时,该函数返回值2,否则返回值3
当然值1,值2,值3也可以是表达式,这个函数使得某些sql语句简单了许多
使用方法:
1、比较大小
select decode(sign(变量1-变量2),-1,变量1,变量2) from dual; --取较小值
sign()函数根据某个值是0、正数还是负数,分别返回0、1、-1
例如:
变量1=10,变量2=20
则sign(变量1-变量2)返回-1,decode解码结果为“变量1”,达到了取较小值的目的。
2、此函数用在SQL语句中,功能介绍如下:
Decode函数与一系列嵌套的 IF-THEN-ELSE语句相似。base_exp与compare1,compare2等等依次进行比较。如果base_exp和 第i 个compare项匹配,就返回第i 个对应的value 。如果base_exp与任何的compare值都不匹配,则返回default。每个compare值顺次求值,如果发现一个匹配,则剩下的compare值(如果还有的话)就都不再求值。一个为NULL的base_exp被认为和NULL compare值等价。如果需要的话,每一个compare值都被转换成和第一个compare 值相同的数据类型,这个数据类型也是返回值的类型。
Decode函数在实际开发中非常的有用
结合Lpad函数,如何使主键的值自动加1并在前面补0
select LPAD(decode(count(记录编号),0,1,max(to_number(记录编号)+1)),14,'0') 记录编号 from tetdmis
eg:
select decode(dir,1,0,1) from a1_interval
dir 的值是1变为0,是0则变为1
比如我要查询某班男生和女生的数量分别是多少?
通常我们这么写:
select count(*) from 表 where 性别 = 男;
select count(*) from 表 where 性别 = 女;
要想显示到一起还要union一下,太麻烦了
用decode呢,只需要一句话
select decode(性别,男,1,0),decode(性别,女,1,0) from 表
3,order by对字符列进行特定的排序
大家还可以在Order by中使用Decode。
例:表table_subject,有subject_name列。要求按照:语、数、外的顺序进行排序。这时,就可以非常轻松的使用Decode完成要求了。
select * from table_subject order by decode(subject_name, '语文', 1, '数学', 2, , '外语',3)
转载地址:http://www.cnblogs.com/juddhu/archive/2012/03/07/2383101.html
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- oracle中的decode的使用
- LeetCode 011. Container With Most Water
- SoapObject result=(SoapObject)envelope.getResponse(); 这个有时候会出现转换异常。
- IOS系列—— UINavigationController隐藏后手势返回不可用
- 黑马程序员——一个古老的悖论
- c++中的虚函数
- oracle中的decode的使用
- linux机器间文件拷贝
- 剑指offer面试题4—替换空格
- Web开发基本准则
- 求职面试的时候如何谈薪酬待遇
- 始终都无法删除Cookie
- How to solve the Candy problem?
- 幸福和成功的十条诫律
- NYOJ 比大小