Oracle中decode函数和sign函数的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39859824/article/details/84108380

数据库表结构如下:

流程控制函数 DECODE

decode()函数简介:

主要作用:

将查询结果翻译成其他值(即以其他形式表现出来,以下举例说明);

使用方法:

Select decode(columnname,值1,翻译值1,值2,翻译值2,…值n,翻译值n,缺省值)

From talbename

Where …

其中columnname为要选择的table中所定义的column,

含义解释:

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

注:其中缺省值可以是你要选择的column name 本身,也可以是你想定义的其他值,比如Other等;

举例说明:

现定义一table名为output,其中定义两个column分别为monthid(var型)和sale(number型),若sale值=1000时翻译为D,=2000时翻译为C,=3000时翻译为B,=4000时翻译为A,如是其他值则翻译为Other;

SQL如下:

Select monthid,decode(sale,1000,'D',2000,'C',3000,'B',4000,'A',’Other’) sale from output

特殊情况:

若只与一个值进行比较

Select monthid ,decode(sale, NULL,‘---’,sale) sale from output

另:decode中可使用其他函数,如nvl函数或sign()函数等;

比较大小函数 sign

函数语法:
sign(n)

函数说明:
取数字n的符号,大于0返回1,小于0返回-1,等于0返回0

示例:
1、select sign( 100 ),sign(- 100 ),sign( 0 ) from dual;

  SIGN(100) SIGN(-100) SIGN(0)
  ———- ———- ———-
  1 -1 0

2、a=10,b=20 
  则sign(a-b)返回-1

现在的需求是:在要用decode函数实现以下几个功能:成绩>85,显示优秀;>70显示良好;>60及格;否则是不及格。

select name, decode(sign(score-85),1,'优秀',0,'优秀',-1, 
decode(sign(score-70),1,'良好',0,'良好',-1, 
decode(sign(score-60),1,'及格',0,'及格',-1,'不及格'))) 
from test;

结果如下图所示:

需要注意的是:mysql里面是没有decode函数的,如果需要实现上述效果,可以用case when函数来实现。

 select name,score,(case when score >=85 then '优'
when score between 75 and 84 then '良'
when score between 60 and 74 then '及格'
when score <60 then '不及格'
when score is null then '缺考' end) 分数等级评价
from test;

猜你喜欢

转载自blog.csdn.net/qq_39859824/article/details/84108380