MySql 中关键字 case when then else end 的用法

 

MySql 中关键字 case when then else end 的用法

解释:

SELECT            
     case                   -------------如果
     when sex='1' then '男' -------------sex='1',则返回值'男'
     when sex='2' then '女' -------------sex='2',则返回值'女'  
     else '其他'                 -------------其他的返回'其他’
     end                    -------------结束
 from   sys_user            --------整体理解: 在sys_user表中如果sex='1',则返回值'男'如果sex='2',则返回值'女' 否则返回'其他’

--- 用法一: 

 

SELECT            
     case                   -------------如果
     when sex='1' then '男' -------------sex='1',则返回值'男'
     when sex='2' then '女' -------------sex='2',则返回值'女'  
     else '其他'                 -------------其他的返回'其他’
     end                    -------------结束
 from   sys_user            --------整体理解: 在sys_user表中如果sex='1',则返回值'男'如果sex='2',则返回值'女' 否则返回'其他’

 

---用法二:

 

1 SELECT STATE
2             CASE WHEN '1' THEN '成功' 
3                  WHEN '2' THEN '失败'
4             ELSE '其他' END  
5             FROM  SYS_SCHEDULER

 

例子:

 

1 有员工表empinfo 
 2 ( 
 3 Fempno varchar2(10) not null pk, 
 4 Fempname varchar2(20) not null, 
 5 Fage number not null, 
 6 Fsalary number not null 
 7 ); 
 8 假如数据量很大约1000万条;写一个你认为最高效的SQL,用一个SQL计算以下四种人: 
 9 fsalary>9999 and fage > 35 
10 fsalary>9999 and fage < 35 
11 fsalary <9999 and fage > 35 
12 fsalary <9999 and fage < 35 
13 每种员工的数量; 
14 select sum(case when fsalary > 9999 and fage > 35
15 then 1
16 else 0end) as "fsalary>9999_fage>35",
17 sum(case when fsalary > 9999 and fage < 35
18 then 1
19 else 0
20 end) as "fsalary>9999_fage<35",
21 sum(case when fsalary < 9999 and fage > 35
22 then 1
23 else 0
24 end) as "fsalary<9999_fage>35",
25 sum(case when fsalary < 9999 and fage < 35
26 then 1
27 else 0
28 end) as "fsalary<9999_fage<35"
29 from empinfo;

 

原文链接:https://www.cnblogs.com/anche/p/9038802.html

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值