sql中的case函数

 在sql中case是一个控制流语句;类似于if语句

Case语句有两种形式:简单case语句与搜索case语句;

简单的case语句:可以检查表达式的值与一组唯一值的匹配:

语法:

 Case expression

  When  value1 then returnvaluse1

  When  value2 then returnvaluse2

  Else  defaultvalue

  End

Case函数对表达式expression进行测试,如果expression等于value1则returnvaluse1,依次类推如果returnvaluse1不符合所有的when,就返回defaultvalue.

例:查出成绩为40的人

 --create database score

 create table sc(

 sc_id int  identity(1,1) primary key,

 sc_name nvarchar(255),

 sc_performance int ,

 sc_grade nvarchar(10),

 check(sc_performance<=100)

 )

insert into sc (sc_name,sc_performance,sc_grade) values('小明','80','B' ),

('小红','92','A'),

('张三','70','B'),

('李四','60','C'),

('王五','50','D'),

('王展','90','A'),

('小梦','80','B')

  select sc_name,(case sc_performance

 when 40 then '40分'

 end  )from sc

因为没有符合40分的所以都返回空

例:将学生分为评分为A与评分不为A;

select *,(case sc_grade

when 'A' then '评分为A' else '评分不为A'

end) from sc

简单的case语句仅允许你将表达式的值与一组不同的值进行匹配,为了执行更复杂的匹配,如范围,你可以使用可搜索case语句.可搜索case语句等同于if语句,但是它的构造更加可读;

case

When conditon1 then returnvalue1

When conditon2 then returnvalue2

When conditon3 then returnvalue3

else defaultvalue

end

Conditon1~3为条件表达式,case函数对各个表达式从前往后进行测试如果conditon1为真则返回returnvalue1否则如果conditon2为真则返回returnvalue2

例:查出表中及格的与不及格的分别有哪些:

 select *,(case when sc_performance>=60 then '及格'

     when sc_performance<60 then '不及格'

 else '其他'

 end)from sc

例:统计列印各科成绩;

select *,(case when sc_performance<100 and sc_performance>=80 then'1'else 0 end)as [100-80],

(case when sc_performance<80 and sc_performance>=60 then'1'else 0 end)as [80-60],

(case when sc_performance<60    then'1' else 0 end)as 小于60 from sc

小结:本博客分享简单case函数的两种用法一种是简单case语法一种的搜索case语句;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值