case when then else end 及cheak约束

本文深入解析SQL中的Case语句,包括其基本语法、使用场景及注意事项。通过生动的例子,如情感判断、身高分类及薪资约束,展示Case语句在实际数据处理中的强大功能。

语句:case when then else end 

这语句,说简单不简单,说不简单也简单。啧啧 

case:简单函数and搜索函数俩种

case简单函数

case sex when '0' then '男' when '1' then '女' else '做手术?' end

case搜索函数     

case when sex = '0' then '男' when sex = '1' then '女' else '做手术' end

类似if-else语句

例子1:

case 
when '喜欢我吗' in ( '喜欢', '不喜欢') then '不知道'  
when '喜欢我吗' in ('喜欢')  then '她喜欢我'  
else'不喜欢我'end

上述例子中,第三行中的结果会被第二行给拦截下来,结果永远是不知道

你想想多可怕,人家喜欢你你却一直不知道,你不单身谁单身!(敲黑板!!)

例子二:计算喜欢你的人按身高计算数量(想想就激动)

select
case when height <= 1.5 then '1'
when height > 1.5 and height <= 1.6  then '2'
when height > 1.6 and height <= 1.7  then '3' 
else '4' end ,
count(*)
from  love_table
group by
case when height <= 1.5 then '1'
when height > 1.5 and height <= 1.6  then '2'
when height > 1.6 and height <= 1.7  then '3' 
else '4' end 

这样就会得到结果啦

例子三:cheak约束中试用case函数

女朋友工资必须高于6k
 

constraint check_salary check(

           case when sex = '1'

           then case when salary > 6000  then 1 else 0 end

           else 0 end = 1 )

假如单纯使用check,如下所示

constraint check_salary check ( sex = '1' and salary > 6000 )

男性收入的情况将无法填入

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值