假设有关系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)