MySql 中 case when then else end 的用法

轉載自:https://www.cnblogs.com/renpei/p/5485730.htmlhtml

解釋:sql

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',則返回值'女' 不然返回'其餘’code

用法一:htm

SELECT 
            CASE WHEN STATE = '1' THEN '成功' 
                 WHEN STATE = '2' THEN '失敗'
            ELSE '其餘' END  
            FROM  SYS_SCHEDULER

用法二:blog

SELECT STATE
            CASE WHEN '1' THEN '成功' 
                 WHEN '2' THEN '失敗'
            ELSE '其餘' END  
            FROM  SYS_SCHEDULER

列子:get

有員工表empinfoclass

( 
Fempno varchar2(10) not null pk, 
Fempname varchar2(20) not null, 
Fage number not null, 
Fsalary number not null 
);

假如數據量很大約1000萬條;寫一個你認爲最高效的SQL,用一個SQL計算如下四種人:select

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;
相關文章
相關標籤/搜索