MySQL Case When 用法

case具有两种格式。简单case函数和case搜索函数。

1、简单case函数:

    case sex
    when '1' then ''
    when '2' then ''
    else '其他' end

2、case搜索函数:

    case when sex = '1' then ''
    when sex = '2' then ''
    else '其他' end

这两种方式,可以实现相同的功能。简单case函数的写法相对比较简洁,但是和case搜索函数相比,功能方面会有些限制,比如写判定式。 

例如:

select grouping_authorizations.group as '授权分组',count(id) as '总用户数',sum(case when is_authorize=1 then 1 else 0 end) as '授权用户数',sum(case when is_authorize=2 then 1 else 0 end) as '未授权用户数' from grouping_authorizations group by grouping_authorizations.group;

Enjoy it !

原文地址:https://www.cnblogs.com/daizhongxing/p/13278215.html