sql学习-case when

当需要对数据按条件进行统计或者处理时,需要用到case when.

1.case when的经典结构为:

select column1,column2,
case

when 条件1 then 结果1

when 条件2 then 结果2

else 结果3

END AS newColumn
from table;

  2. case when 的下述两种表达方式是等效的:

case 
when tb1.os = 'android' then 'android'
when tb1.os = 'ios' then 'iPhone'
else 'PC'
end as os,
case tb1.os
when 'android' then 'android'
when 'ios' then 'iPhone'
else 'PC'
end as os,

3.应用举例:

3.1)增加一个新列

      

3.2)与group连用,并且增加多个新列

create table testScore    
(       
   tname varchar(30) null,    
   ttype varchar(10) null,    
   tscor int null   
);    
 
insert into testScore values ('张三','语文',80);   
insert into testScore values ('张三','数学',98);    
insert into testScore values ('张三','英语',65);    
insert into testScore values ('李四','语文',70);    
insert into testScore values ('李四','数学',80);    
insert into testScore values ('李四','英语',90);    
 
 
select
    tname as '姓名' ,     
    max(case ttype when '语文' then tscor else 0 end) '语文',     
    max(case ttype when '数学' then tscor else 0 end) '数学',     
    max(case ttype when '英语' then tscor else 0 end) '英语'     
from testScore     
group by tname

 结果为:

3.3)case when 与sum联用 

select depend_name,
             sum( case when dt>=date_add(CURRENT_DATE(),-1) then 1 else 0 end) as tb_call_times1,    
             sum( case when dt>=date_add(CURRENT_DATE(),-8) then 1 else 0 end) as tb_call_times7, 
             count(1) as tb_call_times30,
             concat(max(dt),' 00:00:00') as access_time
            from odm.odm_inn_etl_sched_trigger_depend_s_d where dt>add_months(CURRENT_DATE(),-1) and enable=1   
            group by depend_name 

注:文档参考sql语言中group by和case when及sum(case when)的结合使用_group by case when_风神修罗使的博客-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值