zoukankan      html  css  js  c++  java
  • SQL中 decode()函数简介

      今天看别人的SQL时看这里面还有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()函数等;

    NVL(EXPR1,EXPR2)

    若EXPR1是NULL,则返回EXPR2,否则返回EXPR1.

    SELECT NAME,NVL(TO_CHAR(COMM),'NOT APPLICATION') FROM TABLE1;

    如果用到decode函数中就是

    select monthid,decode(nvl(sale,6000),6000,'NG','OK') from output

     

    sign()函数根据某个值是0、正数还是负数,分别返回0、1、-1,

    如果取较小值就是

    select monthid,decode(sign(sale-6000),-1,sale,6000) from output,即达到取较小值的目的。

  • 相关阅读:
    Python元组、列表、字典
    测试通过Word直接发布博文
    Python环境搭建(windows)
    hdu 4003 Find Metal Mineral 树形DP
    poj 1986 Distance Queries LCA
    poj 1470 Closest Common Ancestors LCA
    poj 1330 Nearest Common Ancestors LCA
    hdu 3046 Pleasant sheep and big big wolf 最小割
    poj 3281 Dining 最大流
    zoj 2760 How Many Shortest Path 最大流
  • 原文地址:https://www.cnblogs.com/freespider/p/1795977.html
Copyright © 2011-2022 走看看