Decode函数说明以及纵横表的转化

Decode函数说明

含义解释: 

  • decode(字段或字段的运算,值1,值2,值3)

         这个函数运行的结果是,当字段或字段的运算的值等于值1时,该函数返回值2,不然返回值3
    固然值1,值2,值3也能够是表达式,这个函数使得某些sql语句简单了许多sql

 

  • 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函数

 


 

用法

1.比较大小

select decode( sign(a.salesprice-a.wholesalesprice), --sign 函数大于0返回1,小于0返回-1,0返回0
0,'同样', '1','价格大', '-1','价格小'), a.salesprice,a.wholesalesprice from hrip.dict_item_charge a

 

2.统计数量

select 
sum(decode(p.sexname,'',1,0)) 男的数量, sum(decode(p.sexname,'',1,0)) 女的数量 from hrip.pati_info_basic p

 

3.子查询

select decode(b.sexname, '',(select w.patiid from hrip.pati_info_workunit w where w.patiid = b.patiid), '',(select w.patiid from hrip.pati_info_workunit w where w.patiid = b.patiid), '不清楚性别') from hrip.pati_info_basic b

 

其余

  • 此函数Oracle专用,还能够用于字符串搜索,主键值加一等,灵活运用。

 

ORACLE中纵横表的转化

假设有张学生成绩表(zb)以下:post

我如今我须要获得以下的数据spa

用DECODE或者CASE来实现相互转化:翻译

select name 姓名, max(case subject when '语文' then result else 0 end) 语文, max(case subject when '数学' then result else 0 end) 数学, max(case subject when '物理' then result else 0 end) 物理 from zb group by name; ---------------------------------------------------------------------- select name 姓名, max(decode(subject, '语文', result, 0)) 语文, max(decode(subject, '数学', result, 0)) 数学, max(decode(subject, '物理', result, 0)) 物理 from zb group by name;

这两个语句均可以实现咱们的需求。code

反之:blog

select *
  from (select 姓名 as Name, '语文' as Subject, 语文 as Result from hb union all
        select 姓名 as Name, '数学' as Subject, 数学 as Result from hb union all
        select 姓名 as Name, '物理' as Subject, 物理 as Result from hb) t order by name, case Subject when '语文' then
             1
            when '数学' then
             2
            when '物理' then
             3
          end;

 

此时咱们还能够增长总分,平均分的字段:ip

select *
  from (select 姓名 as Name, '语文' as Subject, 语文 as Result from hb union all
        select 姓名 as Name, '数学' as Subject, 数学 as Result from hb union all
        select 姓名 as Name, '物理' as Subject, 物理 as Result from hb) t order by name, case Subject when '语文' then
             1
            when '数学' then
             2
            when '物理' then
             3
          end;
相关文章
相关标签/搜索