MySql 中 case when then else end 的用法

來源:互聯網
上載者:User

標籤:state   結束   員工   varchar   www   sel   其他   http   arc   

 

解釋:

SELECT            
    case                   -------------如果
    when sex=‘1‘ then ‘男‘ -------------sex=‘1‘,則傳回值‘男‘
    when sex=‘2‘ then ‘女‘ -------------sex=‘2‘,則傳回值‘女‘  
    else 0                 -------------其他的返回‘其他’
    end                    -------------結束
from   sys_user            --------整體理解: 在sys_user表中如果sex=‘1‘,則傳回值‘男‘如果sex=‘2‘,則傳回值‘女‘ 否則返回‘其他’

---用法一:
SELECT 
            CASE WHEN STATE = ‘1‘ THEN ‘成功‘ 
                 WHEN STATE = ‘2‘ THEN ‘失敗‘
            ELSE ‘其他‘ END  
            FROM  SYS_SCHEDULER
---用法二:    
SELECT STATE
            CASE WHEN ‘1‘ THEN ‘成功‘ 
                 WHEN ‘2‘ THEN ‘失敗‘
            ELSE ‘其他‘ END  
            FROM  SYS_SCHEDULER

 

 

列子:

有員工表empinfo 

Fempno varchar2(10) not null pk, 
Fempname varchar2(20) not null, 
Fage number not null, 
Fsalary number not null 
); 
假如資料量很大約1000萬條;寫一個你認為最高效的SQL,用一個SQL計算以下四種人: 
fsalary>9999 and fage > 35 
fsalary>9999 and fage < 35 
fsalary <9999 and fage > 35 
fsalary <9999 and fage < 35 
每種員工的數量; 
select sum(case when fsalary > 9999 and fage > 35
then 1
else 0end) as "fsalary>9999_fage>35",
sum(case when fsalary > 9999 and fage < 35
then 1
else 0
end) as "fsalary>9999_fage<35",
sum(case when fsalary < 9999 and fage > 35
then 1
else 0
end) as "fsalary<9999_fage>35",
sum(case when fsalary < 9999 and fage < 35
then 1
else 0
end) as "fsalary<9999_fage<35"
from empinfo;

MySql 中 case when then else end 的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.