分支结构case……end

语法:

case

when 条件1 then 结果1

when 条件2 then 结果2

………..

else 其它结果

end

执行顺序:

条件1成立执行结果1

条件2成立执行结果2

如果所有的when中条件都不成立,则执行else中的结果

说明:

else可省略,如果省略else并且when的条件表达式的结果都不为true,则case返回值null

列子:
        采用ABCD的形式为学生成绩评分
        A 90分以上
        B 80分以上
        C 70分以上
        D 60分以上
        E 60分以下
解:
    declare @ a int            --声明@a 是变量
    set @a =93               --为变量赋值
    
select 成绩=case
when @a >=90 then ‘A’
when @a >=80 and @a <=89 then ‘B’
when @a between 70 and 79 then ‘C’
when @a between 60 and 69 then ‘D’
else ‘E’
end
go          这里的between……and 在什么什么之间

case…..end 在sql语句中的使用
    购买为1次的为普通会员,2-5次为白金会员,6-10次为VIP会员 10次以上为VIP白金会员。
    select 用户好=userid,次数=case    
                            when count (*)=1 then ‘普通会员’
                            when count(*) between 2 and5then‘白金会员’
                            when count(*) between 6 and 10 ‘vip会员’
                            end 
                                from orderinfo group by userid (serid和次数要分级)
原文地址:https://www.cnblogs.com/xiaowie/p/8675758.html