sql server case表达式
在sql server中,在处理条件分支时,使用case表达式十分便利,对于case的表达基本用法很简单,但它还有一些我们意想不到的写法,可以为我们的sql优化,起到事半功倍的效果。
1.常用select用法
例如:
在人物表中对于性别列,我们可以使用数字1表示男,2表示女,0表示其他,在搜索表示数据时,使用case表达式如下:
--简单case表达式写法 select id, name, age, case sex when '1' then '男' when '2' then '女' else '未知' end as 性别 from dbo.person --搜索case表达式 select id, name, age, case when sex= '1' then '男' when sex= '2' then '女' else '未知' end as 性别 from dbo.person
这里的两种写法,简单表达式和搜索表达式效果是一样的,可以根据自己喜好写。
注意事项:
当case表达式执行时,匹配到第一个when时,执行就结束了,后面的when条件不会再去匹配,所以要注意条件范围大小的顺序。尽量写else条件,否则显示的数据可能是你意料之外的。
2.update中使用case表达式
当需要更新某个字段需要面对多种情况时,一般由对最底层的条件依次往上多次去更新,这样很容易出现事故,使用case 表达式可以一次更新。
例如:
针对一张分数表,分数在 [60-70) 内分数 * 0.6,分数在 [70-80) 内分数 * 0.7,分数在 [80-90) 内分数 * 0.8,分数在 [90-100] 内分数 * 0.9。
分数表如下:
如果按条件一步步去更新,这里一定不能先去更新[90-100]分数段的成绩,因为这个分数段的成绩更新后成绩在[81-90]范围内,会被后面的更新再次更新,所以只能从最底层条件[60-70)条件往上依次多次去更新。
如果使用case表达式可以一次更新所有情况
update score set score= case when score>=90 and score<=90 then score*0.9 when score>=80 and score<90 then score*0.8 when score>=70 and score<80 then score*0.7 when score>=60 and score<70 then score*0.6 else score end
3.group by 聚合函数中使用case表达式
针对分数表统计出学生各学科成绩,
如下表:personid为学号,subject:1为语文,2为数学,3为英语。
select personid, sum(case when subject=1 then score else 0 end) as '语文', sum(case when subject=2 then score else 0 end) as '数学', sum(case when subject=3 then score else 0 end) as '英语' from score group by personid
实现结果:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论