关于case when then 的浅析

【学习点点滴滴】 要对case when then  的用法进行说明,我认为我们弄清case 的两种用法即可,当然只是浅析,在此也感谢CSDN里的兄弟给我的解答。下面建个表,运用case when then 语句 对表进行一系列的处理,得到我们想要的结果。来进行说明:

 

(1):建一个表:

create  table ta ([姓名] varchar(10),[课程] varchar(4),[分数] int)
insert ta
select 'sinpoal','语文',85 union all
select 'sinpoal','数学',90 union all
select 'sinpoal','物理',70 union all
select 'sinpoal1','数学',80 union all
select 'sinpoal1','物理',60 union all
select 'sinpoal1','语文',79 union all
select 'sinpoal2','数学',98 union all
select 'sinpoal2','物理',80 union all
select 'sinpoal2','语文',72

--第一步
select 姓名,
case when 课程='语文' then  分数  end  语文,
case when 课程='数学' then  分数   end 数学,
case when 课程='物理' then 分数  end 物理
from ta
 
/*


姓名        语文          数学          物理
----     -----------    -----------  -----------
sinpoal    85              NULL       NULL
sinpoal    NULL          90           NULL
sinpoal    NULL          NULL       70
sinpoal1  NULL          80           NULL
sinpoal1  NULL          NULL       60
sinpoal1  79              NULL       NULL    
sinpoal2  NULL          98           NULL
sinpoal2  NULL          NULL       80
sinpoal2  72              NULL       NULL

 

--第二步
--(第一种用法)

select 姓名 ,
  max(case 课程 when '语文' then 分数 end )  语文,
  max(case 课程 when '数学' then 分数 end)   数学,
  max(case 课程 when '物理' then 分数  end)  物理
from ta
group by 姓名

 --(第二种用法)

select 姓名 ,
  max(case  when 课程= '语文' then 分数 end )  语文,
  max(case  when 课程='数学' then 分数 end)   数学,
  max(case  when 课程= '物理' then 分数  end)  物理
from ta
group by 姓名

/*
姓名        语文          数学        物理
----     ----------- ----------- -----------
sinpoal    85          90          70
sinpoal1  79          80          60
sinpoal2  72          98          80

 

 

姓名      语文          数学        物理
----    ----------- ----------- -----------
sinpoal    85          90          70
sinpoal1  79          80          60
sinpoal2  72          98          80

 可以看到两种用法对结果没有影响,但值得一说的是,后者可以加条件*/


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值