Oracle中case when语句的用法.

case when语法:

case
when<A> then<somethingA>
when<B> then<somethingB>
else<somethingE>
end

case when else语法要点说明如下:
1、以CASE开头,以END结尾
2、分支中WHEN 后跟条件,THEN为显示结果
3、ELSE 为除此之外的默认情况,类似于高级语言程序中switch case的default,可以不加
4、END 后跟别名

例1:

select u.user_code, u.sex,
( case u.sex
  when 0 then '男'
  when 1 then '女'
  else '未知'
  end
)性别
from tb_secure_user u

例2:将sum与case结合使用,可以实现分段统计,如将表中各种性别的人数进行统计:

select
     sum( case u.sex when 0 then 1 else 0 end) 男性,
     sum( case u.sex when 1 then 1 else 0 end ) 女性,
     sum( case when u.sex<>0 and u.sex<>1 then 1 else 0 end ) 性别未知
from tb_secure_user u

查询结果:

    男性 女性 性别未知
    20    17     0

例3:sum、case when结合group by使用,可以进行分组分段统计。

         如统计users表中每个创建者创建的男性、女性的用户总数

select u.create_user_id 创建者ID,
     sum( case u.sex when 0 then 1 else 0 end) 男性,
     sum( case u.sex when 1 then 1 else 0 end ) 女性,
     sum( case when u.sex<>0 and u.sex<>1 then 1 else 0 end ) 性别未知
from tb_secure_user u
group by u.create_user_id

查询结果:

 创建者ID 男性 女性 性别未知
 10000000 14 8 0
 00000405 4 8 0
 20000000 1 0 0
 00000445 1 1 0

猜你喜欢

转载自wjlvivid.iteye.com/blog/1609736