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