但行好事
莫论前程❤

Oracle CASE WHEN 用法介绍

1. 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 

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

  • 2.1 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;
select ect.pk_corporation pk_corporation,
       ect.pk_person pk_person,
       sum( case 
              when eptd.pk_accounttype in ('PPT000','PPG000')  then 
                    eptd.transferin_balance
              else
                0
           end) psn_contr_balance,
       sum( case 
              when eptd.pk_accounttype in ('PCT000','PCG000')  then 
                    eptd.transferin_balance
              else
                0
           end) corp_contr_balance,
from eprk_corp_transferin  ect
inner join eprk_person_transferin_detail  eptd
    on ect.pk_corp_transferin = eptd.pk_corp_transferin
 where ect.pk_corp_transferin = ? 
  • 2.3 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的其他实现

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%')
赞(0) 打赏
未经允许不得转载:刘鹏博客 » Oracle CASE WHEN 用法介绍
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏