SQL学习笔记——case表达式

语法:

select <列名>,
case when <求值表达式> then <表达式>
     when <求值表达式> then <表达式>
     when <求值表达式> then <表达式>
     .. .
     else <表达式>
end
from <表名>

when 子句中的“< 求值表达式>”就是类似“列 = 值”这样,返回值为真值。case 表达式会从对最初的when子句中的“< 求值表达式>”进行求值开始执行。如果结果为真(true),那么就返回then子句中的表达式,该条case表达式的执行到此为止,继续执行下一条。如果结果不为真,那么就跳转到下一条when子句的求值之中。如果直到最后的when子句为止返回结果都不为真,那么就会返回else
中的表达式,执行终止。

else子句也可以省略不写,这时会被默认为else null。此外,case表达式最后的“end”是不能省略的。

--搜索型case表达式
select product_name,
       case product_type
            when '衣服' then concat('A :' , product_type)
            when '办公用品' then concat('B :' , product_type)
            when '厨房用具' then concat('C :' , product_type)
            else null
       end as abc_product_type
from product;

--简单型case表达式
select product_name,
       case when product_type = '衣服' then concat('A :' , product_type)
            when product_type = '办公用品' then concat('B :' , product_type)
            when product_type = '厨房用具' then concat('C :' , product_type)
            else null
       end as abc_product_type
from product;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值