mysql 中 case when then .... else end 的简单使用

数据SQL CASE 表达式是一种通用的条件表达式,类似于其它语言中的 if/else 语句。 

CASE WHEN condition THEN result 

   WHEN condition THEN result 

   .............
   [WHEN ...] 
   [ELSE result] 
END 

CASE 子句可以用于任何表达式可以有效存在的地方。 condition 是一个返回boolean 的表达式。 如果结果为真,那么 CASE 表达式的结果就是符合条件的 result。 如果结果为假,那么以相同方式搜寻任何随后的 WHEN 子句。 如果没有 WHEN condition 为真,那么 case 表达式的结果就是在 ELSE 子句里的值。 如果省略了 ELSE 子句而且没有匹配的条件, 结果为 NULL。

或其语法为:

简单Case函数 
CASE sex 
         WHEN '1' THEN '男' 
         WHEN '2' THEN '女' 
ELSE '其他' END 

建议都使用第一种,少记点,也好理解。

例子:如下某学校在2005和2006年比赛的数据,

 

1)将 win_loss 中的胜,负,平 都变成 对应的 ‘win’,'loss','tie'

select date_year,
    case 
    when win_loss='' then 'win'
    when win_loss='' then 'loss' 
    else 'tie' 
    end win_loss
    from scores;

2) 假设胜得3分,平得一分,负得0分,统计每一年的得分

select date_year ,
sum(case when win_loss='' then 3 when win_loss='' then 1 else 0 end ) score 
from scores group by date_year;

3)统计每一年的 胜场数,平场数 和 负场数

select date_year ,
sum(case when win_loss='' then 1 else 0 end ) '胜场数' ,
sum(case when win_loss='' then 1 else 0 end) '负场数',
sum(case when win_loss='' then 1 else 0 end) '平场数' 
from scores group by date_year;

由例一可以发现,使用 case when  then  else then 时 是每一条语句都去执行一遍。

例二:数据集如下:

 

试试看:

select tname, case when ttype = '语文' then tscor else 0 end from testScore

1)用一行来显示一个学生的成绩

select tname, tscor
from testScore group by tname;

select tname, 
(case when ttype='语文' then tscor else 0 end) '语文', 
(case when ttype ='数学' then tscor else 0 end) '数学', 
(case when ttype ='英语' then tscor else 0 end) '英语'
from testScore group by tname;

select
    tname as '姓名' ,     
    max(case ttype when '语文' then tscor else 0 end) '语文',     
    max(case ttype when '数学' then tscor else 0 end) '数学',     
    max(case ttype when '英语' then tscor else 0 end) '英语'     
from testScore     
group by tname;
select tname, 
max(case  when ttype='语文' then tscor else 0 end) '语文', 
max(case when ttype ='数学' then tscor else 0 end) '数学', 
max(case when ttype ='英语' then tscor else 0 end) '英语'
from testScore group by tname;

这两是是同样的结果。

对比上面,聚和函数的作用。。。。??

 2)统计学生文科,理科的总分。

select tname as '姓名',
       case
        when ttype='数学' then '理科' else '文科' end as '科别',
        sum(tscor) as '总分'
    from testScore
    group by tname,
             case 
             when ttype='数学' then '理科' else '文科' end ;

 

posted on 2018-08-17 22:45  sprus_timmy  阅读(57704)  评论(0编辑  收藏  举报