在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语句;