oracle case when 语句

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

CASE WHEN 表达式有两种形式

  • 简单Case函数
CASE sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE '其他' END
  • Case搜索函数
CASE
WHEN sex = '1' THEN '男'
WHEN sex = '2' THEN '女'
ELSE '其他' END

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

SELECT CASE WHEN 用法

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;

WHERE CASE WHEN 用法

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

GROUP BY CASE WHEN 用法

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;

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

DECODE() 函数

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

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

使用

更新

UPDATE HBBZ_2015_ALL SET pf=
CASE WHEN (trim(pfbz) in ('0','国0','国O','黄标0')) THEN '0'
WHEN (trim(pfbz) in ('1','国1','国I','国Ⅰ','黄标Ⅰ','绿标Ⅰ')) THEN '1'
WHEN (trim(pfbz) in ('2','国2','国II','国Ⅱ','黄标Ⅱ','黄标Ⅱ','绿标Ⅱ')) THEN '2'
WHEN (trim(pfbz) in ('3','国3','国III','国Ⅲ','绿标Ⅲ')) THEN '3'
WHEN (trim(pfbz) in ('4','国4','国IV','国Ⅳ','国Ⅳ','绿标Ⅳ')) THEN '4'
WHEN (trim(pfbz) in ('5','国5','国V','国Ⅴ','绿标Ⅴ')) THEN '5'
ELSE null END;
commit;

统计

select fzjg,
--注销数
count(case when zxyy<>'M' and zxyy<>'P' and instr(zt,'P')=0 then 1 else null end) zs_zx,
count(case when zxyy<>'M' and zxyy<>'P' and instr(zt,'P')=0 and hbc is not null then 1 else null end) hbc_zx,
count(case when zxyy<>'M' and zxyy<>'P' and instr(zt,'P')=0 and hbc is not null
and ccdjrq < to_date('20060101','yyyymmdd')
and syxz in('B','C','D','E','F','G','N','R') then 1 else null end) hbc2005_zx from table_a group by fzjg order by fzjg;
上一篇:[LeetCode OJ] Candy


下一篇:Active MQ 传输 ObjectMessage 异常