Oracle 中 decode 函数用法

含义解释:
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
decode(字段或字段的运算,值1,值2,值3)

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


create table table_subject
(
   "id" int primary key not null,
   subject_name varchar2(20)  not null,
   score int not null
)

create sequence subject_seq ;

insert into table_subject values(subject_seq.nextval,'语文',98);
insert into table_subject values(subject_seq.nextval,'英语',67);
insert into table_subject values(subject_seq.nextval,'数学',90);
insert into table_subject values(subject_seq.nextval,'数学',89);
insert into table_subject values(subject_seq.nextval,'语文',97);
insert into table_subject values(subject_seq.nextval,'语文',96);
insert into table_subject values(subject_seq.nextval,'语文',95);
insert into table_subject values(subject_seq.nextval,'英语',78);

select * from table_subject group by subject_name;
--按照中文指定字段排序(语文、数学、英语)
--其中1,2,3 代表显示的顺序
select * from table_subject order by decode(subject_name, '语文', 1, '数学', 2 ,'英语',3);




select * from table_subject order by decode(subject_name, '语文', 3, '数学', 2 ,'英语',1);

-- 一条语句统计语数英的数量
select 
  sum(decode(subject_name,'语文',1,0)) as "语文",
  sum(decode(subject_name,'数学',1,0)) as "数学",
  sum(decode(subject_name,'英语',1,0)) as "英语" 
from table_subject;


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值