您好,登錄后才能下訂單哦!
[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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。