1. 程式人生 > >第3章 SQL 習題 - 3.5

第3章 SQL 習題 - 3.5

假設有關係marks(ID,score),我們希望基於如下標準為學生評定等級:如果score < 40 得F;如果40<=score<60得C;如果60<=score<80得B;如果80<=score得A。寫出SQL查詢完成下列操作:

為了學生操作,首先建立關係:

create table marks(
	ID varchar not null,
	score int,
	primary key(ID)
);

再新增一些樣本資料:

insert into marks values(1, 10);insert into marks values(2, 20);
insert into marks values(3, 30);insert into marks values(4, 40);
insert into marks values(5, 40);insert into marks values(6, 60);
insert into marks values(7, 70);insert into marks values(8, 80);
insert into marks values(9, 90);insert into marks values(10, 100);

 執行後,檢視插入結果:

select * from marks;
 id | score 
----+-------
 1  |    10
 2  |    20
 3  |    30
 4  |    40
 5  |    40
 6  |    60
 7  |    70
 8  |    80
 9  |    90
 10 |   100
(10 rows)

a.基於marks關係顯示每個學生的等級。

select ID, score, (case
					when score < 40 then 'F'
					when 40<= score and score <60 then 'C'
					when 60<= score and score <80 then 'B'
					else 'A'
				   end) as class
from marks;

輸出結果如下:

 id | score | class 
----+-------+-------
 1  |    10 | F
 2  |    20 | F
 3  |    30 | F
 4  |    40 | C
 5  |    40 | C
 6  |    60 | B
 7  |    70 | B
 8  |    80 | A
 9  |    90 | A
 10 |   100 | A
(10 rows)

b.找出各等級的學生數。

select (case
					when score < 40 then 'F'
					when 40<= score and score <60 then 'C'
					when 60<= score and score <80 then 'B'
					else 'A'
				   end) as class, count(ID)
from marks group by class order by class;
 class | count 
-------+-------
 A     |     3
 B     |     2
 C     |     2
 F     |     3
(4 rows)