Mysql中case函数的使用

case执行方式:逐一判断每个 WHEN 子句直到返回真值为止。此外,没有能够返回真值的WHEN 子句时,也会返回 ELSE 子句指定的表达式。
用法一:在返回映射时使用(固定字段展示内容)
1)结构

select
    case '数据库字段'
        when '条件1' then '满足条件的结果1'
        when '条件2' then '满足条件的结果2'
        ...
        else '所有条件之外的结果n'
    end as '字段名称'
from t_table;

2)示例(fraction:成绩字段,展示在grade:等级 )

select
    case fraction
        when fraction <![CDATA[<=]]> 100 and fraction <![CDATA[>=]]> 90 then '优秀'
        when fraction <![CDATA[<=]]> 100 and fraction <![CDATA[>=]]> 80 then '中等'
        when fraction <![CDATA[<=]]> 100 and fraction <![CDATA[>=]]> 70 then '良好'
        when fraction <![CDATA[<=]]> 100 and fraction <![CDATA[>=]]> 60 then '及格'
        when fraction <![CDATA[<=]]> 100 and fraction <![CDATA[>=]]> 0 then '不及格'
        else '数据不正确'
    end as grade
from t_table;

用法二:根据特殊字段名称分组并返回
1)结构(需注意,分组的条件需和返回条件一致)

select
    case '数据库字段'
        when '条件1' then '满足条件的结果1'
        when '条件2' then '满足条件的结果2'
        ...
        else '所有条件之外的结果n'
    end as '字段名称'
from t_table
where
	"条件"
group by 
	case '数据库字段'
        when '条件1' then '满足条件的结果1'
        when '条件2' then '满足条件的结果2'
        ...
        else '所有条件之外的结果n'
    end

2)示例(根据描述(dsc)分组,并展示相应的名称,统计数量,<描述为"最多"为一组,其余为一组>)

select
	case dsc
    	when dsc = '最多' then '多'
        else '少'
    end as dsc,
    count(id) as sum
from t_table
where
	sex is not null
group by 
	case dsc
        when dsc = '最多' then '多'
        else '少'
    end
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值