Decode函数说明以及纵横表的转化
Decode函数说明
含义解释:
- decode(字段或字段的运算,值1,值2,值3)
这个函数运行的结果是,当字段或字段的运算的值等于值1时,该函数返回值2,否则返回值3
当然值1,值2,值3也可以是表达式,这个函数使得某些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)如下:
我现在我需要得到如下的数据
用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;
这两个语句都可以实现我们的需求。
反之:
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;
此时我们还可以增加总分,平均分的字段:
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;
自强不息,厚德载物