oracle中的 函数应用

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语句简单了许多

比如我要查询某班男生和女生的数量分别是多少?

通常我们这么写:

select count(*) from 表 where 性别 = 男;

select count(*) from 表 where 性别 = 女;

要想显示到一起还要union一下,太麻烦了

用decode呢,只需要一句话

select sum(decode(性别,男,1,0)),sum(decode(性别,女,1,0)) from 表


 

instr()

俗称:字符查找函数

格式一:instr( string1, string2 )    /   instr(源字符串, 目标字符串)

eg:
select instr('helloworld','l') from dual; --返回结果:3 默认第一次出现“l”的位置 2 select instr('helloworld','lo') from dual; --返回结果:4 即:在“lo”中,“l”开始出现的位置

格式二:instr( string1, string2 [, start_position [, nth_appearance ] ] )   /   instr(源字符串, 目标字符串, 起始位置, 匹配序号)

解析:string2 的值要在string1中查找,是从start_position给出的数值(即:位置)开始在string1检索,检索第nth_appearance(几)次出现string2。

eg:

select instr('helloworld','l',2,2) from dual;  --返回结果:4    也就是说:在"helloworld"的第2(e)号位置开始,查找第二次出现的“l”的位置

 

 

 

猜你喜欢

转载自www.cnblogs.com/2016-cxp/p/9263120.html
今日推荐