码迷,mamicode.com
首页 > 数据库 > 详细

Oracle CASE WHEN 用法介绍

时间:2014-07-24 22:20:52      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:blog   http   使用   strong   re   c   html   代码   

1. CASE WHEN 表达式有两种形式

bubuko.com,布布扣
--简单Case函数  

CASE sex
WHEN ‘1‘ THEN ‘男‘
WHEN ‘2‘ THEN ‘女‘
ELSE ‘其他‘ END

--Case搜索函数

CASE
WHEN sex = ‘1‘ THEN ‘男‘
WHEN sex = ‘2‘ THEN ‘女‘
ELSE ‘其他‘ END
bubuko.com,布布扣

 

2. CASE WHEN 在语句中不同位置的用法

2.1 SELECT CASE WHEN 用法

bubuko.com,布布扣
SELECT   grade, COUNT (CASE WHEN sex = 1 THEN 1      /*sex 1为男生,2位女生*/
ELSE NULL
END) 男生数,
COUNT (CASE WHEN sex = 2 THEN 1
ELSE NULL
END) 女生数
FROM students GROUP BY grade;
bubuko.com,布布扣

 

2.3 WHERE CASE WHEN 用法

bubuko.com,布布扣
SELECT T2.*, T1.*
FROM T1, T2
WHERE (CASE WHEN T2.COMPARE_TYPE = ‘A‘ AND
T1.SOME_TYPE LIKE ‘NOTHING%‘
THEN 1
WHEN T2.COMPARE_TYPE != ‘A‘ AND
T1.SOME_TYPE NOT LIKE ‘NOTHING%‘
THEN 1
ELSE 0
END) = 1
bubuko.com,布布扣

 

2.4 GROUP BY CASE WHEN 用法

bubuko.com,布布扣
SELECT  
CASE WHEN salary <= 500 THEN ‘1‘
WHEN salary > 500 AND salary <= 600 THEN ‘2‘
WHEN salary > 600 AND salary <= 800 THEN ‘3‘
WHEN salary > 800 AND salary <= 1000 THEN ‘4‘
ELSE NULL END salary_class, -- 别名命名
COUNT(*)
FROM Table_A
GROUP BY
CASE WHEN salary <= 500 THEN ‘1‘
WHEN salary > 500 AND salary <= 600 THEN ‘2‘
WHEN salary > 600 AND salary <= 800 THEN ‘3‘
WHEN salary > 800 AND salary <= 1000 THEN ‘4‘
ELSE NULL END;
bubuko.com,布布扣

 

3.关于IF-THEN-ELSE的其他实现

3.1 DECODE() 函数

select decode(sex, ‘M‘, ‘Male‘, ‘F‘, ‘Female‘, ‘Unknown‘)
from employees;

貌似只有Oracle提供该函数,而且不支持ANSI SQL,语法上也没CASE WHEN清晰,个人不推荐使用。

3.2 在WHERE中特殊实现

SELECT T2.*, T1.*
FROM T1, T2
WHERE (T2.COMPARE_TYPE = ‘A‘ AND T1.SOME_TYPE LIKE ‘NOTHING%‘)
OR
(T2.COMPARE_TYPE != ‘A‘ AND T1.SOME_TYPE NOT LIKE ‘NOTHING%‘)

这种方法也是在特殊情况下使用,要多注意逻辑,不要弄错。

引自:

http://www.cnblogs.com/eshizhan/archive/2012/04/06/2435493.html

 

个人记录:

select a.ryh,a.xm,b.cardid,c.szbh,case  when c.sfzx=‘1‘ then ‘1‘ else ‘0‘ end as SFZX from jc a left join sc b on a.ryh = b.ryh left join jx c on a.ryh = c.ryh where cardid is not null 

  

Oracle CASE WHEN 用法介绍,布布扣,bubuko.com

Oracle CASE WHEN 用法介绍

标签:blog   http   使用   strong   re   c   html   代码   

原文地址:http://www.cnblogs.com/biye/p/3866289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!