case when的用法,sql行转列

        我们在平常的开发工作中,经常会使用case when,比如我们需要将某些字段值进行转换,我们需要将数据行转列等,那么都有哪些使用场景呢?

        case when 用法:如果某条数据满足了当前when,则会退出case when,不再执行后面其他case when。

 1:用于字段值得转换,如:查询学生性别,表中存储的为编码:

  case  when  条件  then   值,when  条件  then  值  end

select name,
       (case when sex = '1' then '男'
			 when sex = '2' then '女' end) as '性别'
from student;

       case  when  条件  then   值,when  条件  then  值  else  值  end

select name,
       (case when sex = '1' then '男'
			 when sex = '2' then '女' else '' end) as '性别'
from student;

  2:行转列,如查询每个学生的各科成绩,使用  case when + group  by 实现:

select st.name,st.student_no,
       sum(case when sc.course = '语文' then sc.score end) as '语文',
	   sum(case when sc.course = '数学' then sc.score end) as '数学',
	   sum(case when sc.course = '英语' then sc.score end) as '英语'
from score sc left join student st on sc.student_no = st.student_no GROUP BY 
sc.student_no,st.name

  3:使用case when统计男生和女生的数量:

select
sum(case when sex = '1' then 1 else 0 end) as '男生',
sum(case when sex = '2' then 1 else 0 end) as '女生'
from student;

4:使用case when 判断范围,比如统计各科成绩一般、良好、优秀的人数:

select course,
sum(case when score > 60 and score <=70 then 1 else 0 end) '一般',
sum(case when score > 70 and score <=80 then 1 else 0 end) '良好',
sum(case when score > 80 then 1 else 0 end) '优秀'
from score GROUP BY course;

以上为case when的基本用法,不断的学习,才会遇见更好的自己!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值