理解case表达式

理解case表达式
1基本形式:
    case
 when then
 when then
 else
    end

2如有下数据
id     name               department
3      william silverman  1
4      walt welinski      1
1      carry grant        2
2      michael lancer     2
5      sally fields       3
6      walt frazier       3
7      melissa gomez      4

如果想把部门号转为实际的字符串,可使用以下语句
select id,name,case department
   when 1 then 'marketing'
   when 2 then 'customer service'
   when 3 then 'collictions'
   when 4 then 'customer relations'
  end as dept_name
from employees  order by dept_name

用搜索的case表达式为:
select id,name,case when department=1 then 'marketing'
  when department=2 then 'customer service'
  when department=3 then 'collictions'
  when department=4 then 'customer relations'
  end as dept_name
from employees  order by dept_name

3下面来学习使用case表达式更新列值
如: update employees
    set bonus_level =
  case when total_sales< 1000 then 'rookie'
       when (total_sales >=1000) and (total_sales< 10000) then 'associate'
       when total_sales>10000 then 'vice president'
  end

除了使用实际的字符串外,可将列名和数学表达式用于计算由case表达式返回的值中
如:update employees
 set commission =
  case bonus_level
   when 'rookie' then total_sales * 0.01
   when 'associate' then total_sales * 0.05
   when 'vice president' then total_sales * 0.15
  end

4 使用case表达式避免错误条件
如: select id ,name case when sales_count > 0 then sales_calls/sales_count * 100.0
     else 0
       end as closing_percentage
     from employees where department = 1
     这样就避免了如果sales_count值为null或0时,产生错误。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值