mysql:case when...then...else...end,语句的常用方法举例

case when...then...else...end语句的逻辑为:
case when 条件 then value_a else value_b end该语句表示:当条件成立时,值为value_a,不成立时值取value_b。

用法1: 如果想得到一列布尔值,可以用case when...then...else...end语句得到。
    比如:你有一批渠道号,你想要得到这些渠道号是否属于top50,结果展示方式为“true”和“false”。

    结果展示为这样:

 

    查询语句:select  channel_source,

                     case when channel_source in ('1006186q','1006186r','1009306c','1010184l','1010184m','1010680b','1010680m','1011512a','1011512c','1012046j','1012271f','1012271l','1012490o','1012644c','1015530g','1015530k','1015530l','1015530m','1017549g','1017549h','1017549k','1017549l','1017549v','1018357s','1018357t','1018682n','1018682o','1018682q','1019468p','1019468q','1019468r','1020184a','1020276a','1020539a','1020539b','1020539g','1020539h','1020539i','1020539j','1020539k','1020539l','1020539m','1020539n','1020539o','1020539q','1020539r','1020539s','1020539u','1020539v','1020539w','1000529c','1020539y','1000575g','1020896a','1000561u','1020896d','1020896e','1020896f','1020896g','1020896p','1020896q') then 'true' else 'false' end as top50  

                  --如果channel_source在list(list为top50的渠道号汇总)里面,说明是top50,则返回true,否则返回false

                   from dw_msite_alad_highdown_channel ; 

用法2:case when...then...else...end语句进行逻辑判断,加工得到新的字段。
比如:你有一批用户,他们的资产水平各不相同,你想要对用户进行划分:资产<5000,为普通用户;5000=<资产<50000,为潜力用户;50000=<资产<500000,为高级用户;500000=<资产,为私用银行用户。

结果展示:

 

查询语句: select id ,total_asset,

                  case when total_asset <5000 then '普通用户'

                          when total_asset < 50000 then '潜力用户'  

                          when total_asset < 500000 then '高端用户'  

                          else  '私用银行用户'  

                         end  as type --重新命名为type

                         from  xiaofeishuiping;

用法3:case when...then...else...end语句与sum函数进行分组求和。
比如:想对不同地区的销售额进行求和。

 

结果展示:

 

查询语句: select sum(case when city='b' then price else 0 end) as b_sum,  --当city='b'时为price,否则为0,最后求和并且命名为b_sum。

                   sum(case when city='c' then price else 0 end) as c_sum,

                   sum(case when city='d' then price else 0 end) as d_sum

                    from huizongshuju;

用法4:case when...then...else...end语句按次序进行模糊匹配。
比如:手里有个list( 'ucbrowser', 'baidubox',  'weixin',  'mqqbrowser',  'sogousearch')——各大浏览器按次序排的,

sql里需要匹配的字段长这个样子:.......
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值