Oracle CASE WHEN 用法介紹

來源:互聯網
上載者:User

標籤:blog   http   使用   strong   re   c   html   代碼   

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;

 

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

 

2.4 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;

 

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 

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.