SQL中If,Case的区别与使用

IF函数(类似于三元表达式的效果):

IF(expr,expr_true,expr_false)

当expr为true时,if函数返回expr_true的值;否则返回expr_false的值

eg:

SELECT
	*,
IF
	( stu_sex='男', "1", "0" ) AS sex 
FROM
	stu

在结果集中,stu_sex为男的sex都为1,其余情况为0

IFNULL(expr1,expr2)

当expr1的值不为null时,函数返回expr1;否则返回expr2

SELECT IFNULL(null,"is null")   	-->is null
SELECT IFNULL("not null","expr2")   -->not null

case:用于判断分支

语法:
Case […]
When … then … [When … then …]
[else …]
end

eg:

  1. 在成绩表中按不通过分数段统计人数
统计课程1下,不同分数段的学生人数:
SELECT
	count(case when score<30 then 1 end) as '<30',#then 1 表示该行返回1,则count计数器加1
	count(case when score>29 and score<50 then 1 end) as '29<score<50',
	count(case when score>49 then 1 end ) as '50<'
FROM
	scores
	WHERE course_id=1
  1. case在行中对数据的处理用例
SELECT *
,case 
	when score<30  then '<30' 
	when score>29 and score<50 then "<50" 
	else '>49'
	end as score_area #显示每行不同分值的人所属的分段
,case course_id 
	when 1 then '1_name'
	when 2 then '2_name'
	else '?_name'
	end as course_name #更具课程id转换每行的课程名
FROM scores
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值