SQL中case when的用法

一.单个case when用法
首先,新建一个表:

create table battle(riqi date,result varchar(10))

插入数据:

insert all
       into battle values(to_date('2005-05-09','YYYY-MM-DD'),'win')
       into battle values(to_date('2005-05-09','YYYY-MM-DD'),'lose')
       into battle values(to_date('2005-05-09','YYYY-MM-DD'),'lose')
       into battle values(to_date('2005-05-09','YYYY-MM-DD'),'lose')
       into battle values(to_date('2005-05-10','YYYY-MM-DD'),'win')
       into battle values(to_date('2005-05-10','YYYY-MM-DD'),'lose')
       into battle values(to_date('2005-05-10','YYYY-MM-DD'),'lose')
select 1 from dual;

查看刚才的表:

select * from battle

显示如下:
SQL中case when的用法_第1张图片
现在我们要把所有日期胜利次数,失败次数分别显示出来:
预期表格如下:

riqi win lose
2005-05-09 1 3
2005-05-10 1 2
解决方案一:

case 搜索语句

select riqi, sum(case when result = 'win' then 1 else 0 end) as win, sum(case when result = 'lose' then 1 else 0 end) as lose from battle group by riqi; 

解决方案二:
case普通语句

select riqi, sum(case result when 'win' then 1 else 0 end) as win, sum(case result when 'lose' then 1 else 0 end)as lose from battle group by riqi;

结果如下:
在这里插入图片描述

二、多个case when的使用
有一张表,里面有3个字段:chinese,math,english。其中有一条记录chinese 70分,math 80分,english 58分,请用一条sql语句查询出所有记录并按以下条件显示出来(并写出您的思路):

大于或等于80表示excellent,大于或等于60表示pass,小于60分表示fail。 如下表:

科目 chinese math English
level pass excellent fail
select (case when chinese >= 80 then "excellent" when chinese >= 60 then "pass" else "fail" end) as chinese,  
  
  (case when math >= 80 then "excellent" when math >= 60 then "pass" else "fail" end) as math,  
  
  (case when english >= 80 then "excellent" when english >= 60 then "pass" else "fail" end) as english  
  
  from grade; 

你可能感兴趣的:(SQL)