Case有2中格式:简单Case函数和Case搜索函数。

简单函数:case sex when '1' then '男' when '2' then ‘女’ else  '其它' end;(sex是列)
 
搜索函数:case when sex='1' then '男 ' when sex='2' then '女'
 
实际使用先创建一个表看看
create table t_test(
id number primary key,
matchdate varchar2(12),
resul varchar2(5)
)

 插入简单的数据:

insert into t_test values(1,'2015-02-04','胜');
insert into t_test values(2,'2015-02-04','负');
insert into t_test values(3,'2015-02-04','胜');
insert into t_test values(4,'2015-02-07','负');
insert into t_test values(5,'2015-02-07','胜');
insert into t_test values(6,'2015-02-07','负');

 select * from  t_test 执行的结果

下面使用case函数:

select id,MATCHDATE,case when resul='胜' then 'ok' when resul='负' then 'xx' end 成绩 from t_test;

select id,MATCHDATE,case resul when '胜' then 'ok' when '负' then 'xx' else 'rr' end 成绩 from t_test;

这里的2个是一样的结果;

结果:

可以看到原先的值已经发生改变。

case  when ... then ...      -- 查询 当resul的值为选定值是 then 可做更替,而后的when条件针对多个不同值的改变;

 

统计胜 与负 数量:
select MATCHDATE as 日期,
count(case when RESUL='胜' then RESUL end) as 胜,
count(case when RESUL='负' then RESUL end) as 负
from t_test group by matchdate

 

再搞个例子

create table Table_Country(
name_try varchar2(10),
sex number,
popu number
) 
insert into Table_Country values('中国',1,260);
insert into Table_Country values('中国',2,220);
insert into Table_Country values('美国',1,29);
insert into Table_Country values('美国',2,30);
insert into Table_Country values('加拿大',1,120);
insert into Table_Country values('加拿大',2,56);
insert into Table_Country values('英国',1,50);
insert into Table_Country values('英国',2,60);

 

select name_try,
sum(case sex when 1 then popu end),
sum(case sex when 2 then popu end)
from Table_Country group by name_try

 根据性别分组展示: