MySql 中 case when then else end 的用法

简单函数

语法

selet

CASE 表达式
    WHEN 值1 THEN 值a
    [WHEN 值2 THEN 值b] ...
    [ELSE 值c]
END

FROM 表

解释:

  • 表达式可以是字段,枚举这个字段所有可能的值

例子

select name,

case sex
when 0 then '女'
when 1 then '男'
else '未知'
end as 性别

from emp4

搜索函数

语法

select

CASE
    WHEN 表达式1 THEN 值a
    [WHEN 表达式2 THEN 值b] ...
    [ELSE 值c]
END

from 表

解释:

  • 表达式:可以写判断,可以判断 null

例子

SELECT ename,sal,
    case
    when sal>3000 then '高收入'
    when sal>2000 then '中收入'
        when sal>1000 then '普通收入'
        else '低收入'
    end  as 收入级别
from   emp order by sal

例子

有员工表如下:

empinfo 
( 
Fempno varchar2(10) not null pk, 
Fempname varchar2(20) not null, 
Fage number not null, 
Fsalary number not null 
);

假如数据量很大约1000万条;写一个你认为最高效的SQL,用一个SQL计算以下四种人:

fsalary>9999 and fage > 35 
fsalary>9999 and fage < 35 
fsalary <9999 and fage > 35 
fsalary <9999 and fage < 35

每种员工的数量;

select sum(case when fsalary > 9999 and fage > 35
then 1
else 0
end) as "fsalary>9999_fage>35",
sum(case when fsalary > 9999 and fage < 35
then 1
else 0
end) as "fsalary>9999_fage<35",
sum(case when fsalary < 9999 and fage > 35
then 1
else 0
end) as "fsalary<9999_fage>35",
sum(case when fsalary < 9999 and fage < 35
then 1
else 0
end) as "fsalary<9999_fage<35"
from empinfo;

感谢:
https://www.cnblogs.com/renpei/p/5485730.html


原文出处:/show_1EFhQqz16Lh.html