欢迎各位兄弟 发布技术文章
这里的技术是共享的
[toc]
- 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不能等于一个集合,只能等于某个值,怎么选出某个值?
从图中可以看出,如果我把第一个表取别名为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
来自 https://blog.csdn.net/c13257595138/article/details/88373535