1、语法格式
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(变量1-变量2),-1,变量1,变量2) from dual; --取较小值
sign()函数根据某个值是0、正数还是负数,分别返回0、1、-1
例如:
变量1=10,变量2=20
则sign(变量1-变量2)返回-1,decode解码结果为“变量1”,达到了取较小值的目的。
2)表、视图结构转化举例1:现有一个商品销售表sale,表结构为:
现有数据为:
想要转化为以下结构的数据:
结构转化的SQL语句为:
create or replace view
v_sale(year,month1,month2,month3,month4,month5,month6,month7,month8,month9,month10,month11,month12)
as
select
substr(month,1,4) as 年份,
sum(decode(substr(month,5,2),'01',sell,0)) AS 一月,
sum(decode(substr(month,5,2),'02',sell,0)) AS 二月,
sum(decode(substr(month,5,2),'03',sell,0)) AS 三月,
sum(decode(substr(month,5,2),'04',sell,0)) AS 四月,
sum(decode(substr(month,5,2),'05',sell,0)) AS 五月,
sum(decode(substr(month,5,2),'06',sell,0)) AS 六月,
sum(decode(substr(month,5,2),'07',sell,0)) AS 七月,
sum(decode(substr(month,5,2),'08',sell,0)) AS 八月,
sum(decode(substr(month,5,2),'09',sell,0)) AS 九月,
sum(decode(substr(month,5,2),'10',sell,0)) AS 十月,
sum(decode(substr(month,5,2),'11',sell,0)) AS 十一月,
sum(decode(substr(month,5,2),'12',sell,0)) AS 十二月
from aa_cs
group by substr(month,1,4);
举例2:从我自己做过的项目中摘取的一个实例,目的是对表记录进行分析打印
表结构:
SQL语句:
select
e.equi_type,
ty1.type_name,
e.equi_cd,
e.equi_name,
count(m.equi_cd) as m_count,
(sum(decode(m.maintain_type, '0001', m.total_cost, 0))) AS type1,
(sum(decode(m.maintain_type, '0002', m.total_cost, 0))) AS type2,
(sum(decode(m.maintain_type, '0003', m.total_cost, 0))) AS type3,
(sum(decode(m.maintain_type, '0004', m.total_cost, 0))) AS type4,
(sum(decode(m.maintain_type, '',0,m.total_cost))) AS TOTAL_COST
from equi_maintain m
left join equi_equipment e on m.equi_cd=e.id
left join equi_type ty1 on e.equi_type=ty1.id
group by e.EQUI_CD,e.equi_name,e.equi_type,ty1.type_name order by e.EQUI_CD asc
显示效果为: