温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

oracle菜鸟学习之 select case when的使用

发布时间:2020-07-07 13:37:33 来源:网络 阅读:4949 作者:运维少年 栏目:关系型数据库

[toc]

oracle菜鸟学习之 select case when的使用

格式语法

case
    when 条件1 then action1
    when 条件2 then action2
    when 条件3 then action3
    when 条件N then actionN
    else action
end

例子

判断现在是几月

SQL> select case substr('20181118',5,2)
  2  when '08' then '8yue'
  3  when '09' then '9yue'
  4  when '10' then '10yue'
  5  when '11' then '11yue'
  6  when '12' then '12yue'
  7  else 'other'
  8  end
  9  from dual;

CASESUBSTR('201
---------------
11yue

SQL> 

扩展知识:substr 截取
sbustr('str',x,y)
str:字符串
x:从x位开始
y:x位的后y位结束

SQL> select substr('123456',3,2) from dual;

SUBSTR
------
34

SQL> 

实验

实验表如下:
sno:学号
km:科目
score:成绩
grade:等级

create table score(sno number,km varchar2(8),score int,grade varchar2(4) default null);
insert into score(sno,km,score) values(1,'yw',65);
insert into score(sno,km,score) values(2,'sx',76);
insert into score(sno,km,score) values(3,'yw',86);
insert into score(sno,km,score) values(4,'yw',94);

查看表

SQL> select * from score;

       SNO KM                SCORE GRADE
---------- ------------------------ ---------- ------------
     1 yw                   65
     2 sx                   76
     3 yw                   86
     4 yw                   94

问题:给学生成绩分等级,优秀、良好、中等、合格
思路:先查询学号对应的成绩

SQL> select sno,case
  2  when score >=90 then 'A'
  3  when score >=80 then 'B'
  4  when score >=70 then 'C'
  5  when score >=60 then 'D'
  6  else 'F'
  7  end
  8  from score;

       SNO CAS
---------- ---
     1 D
     2 C
     3 B
     4 A

思路:怎么将等级插入表格?

update score set grade = ?

思路:选出等级的值

select grade from
(select sno,case
 when score >=90 then 'A'
 when score >=80 then 'B'
 when score >=70 then 'C'
 when score >=60 then 'D'
 else 'F'
 end as grade
  9   from score);

GRADE
----------
D
C
B
A

思路:grade不能等于一个集合,只能等于某个值,怎么选出某个值?
oracle菜鸟学习之 select case when的使用

从图中可以看出,如果我把第一个表取别名为a,但a.sno和score.sno相等的时候,grade的值唯一

update score set grade = 
(select grade from
(select sno,case
 when score >=90 then 'A'
 when score >=80 then 'B'
 when score >=70 then 'C'
 when score >=60 then 'D'
 else 'F'
 end as grade
 from score) a
 where a.sno=score.sno
 );

4 rows updated.

查看更新之后的表

SQL> select * from score;

       SNO KM                SCORE GRADE
---------- ------------------------ ---------- ----------
     1 yw                   65 D
     2 sx                   76 C
     3 yw                   86 B
     4 yw                   94 A
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI