Oracle中 decode和 case when then得用法

DECODE函数,是ORACLE公司的SQL软件ORACLE PL/SQL所提供的特有函数计算方式,以其简洁的运算方式,可控的数据模型和灵活的格式转换而闻名。(摘抄)

decode函数得使用

DECODE(value, if1, then1, if2,then2, . . . else )
如:select decode(sex,1,男,女) from table where …
当 sex为 1时,显示男,否则 女;

case when then 多条件用法

如果 when后面得条件为true,则返回then后得值,为false,走下一个when,如果都为false,走 else,没有else,返回空。

case有两种格式 1.简单case函数 2.case搜索函数

简单case 函数

select id,
(case sex when 1 then ‘男’ when 2 then ‘女’ else ‘其他’ end ) sex
from table

case搜索函数

select id.sex,
(case when sex=1 then ‘男’ when sex=2 then ‘女’ else ‘其他’ end) 性别
from table

其中 else 是可选项,如果都不符条件,且没有else 返回null,where可加and ,case可与一些函数相结合,比如sum

统计男女人数

 select   sum(case  sex when 1 then 1 else 0 end ) '男',  --一种写法
			sum(case  when sex =1 then 1 else 0 end ) '男',  --另一种
			sum(case  sex when 2 then 1 else 0 end ) '女',
			sum(case  when sex<>1 and sex<>2  then 1 else 0 end ) '其他'
			from  table

count 统计男女人数

 select   
			count(case  when sex =1 then 'sex'  end ) '男',  
			count(case  when sex =2 then 'sex'  end ) '女',
			count(case  when sex<>1 and sex<>2  then 'sex' end ) '其他'
			from  table
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值