文章目录
- 1.查询出生日期在`1997~1999年`的学生的姓名和专业
- 2.查询`计算机和数学专业`的学生的学号和姓名
- 3.查询姓李并且姓名`只有两个汉字`的学生的学号和姓名
- 4.查询每位学生的每门的成绩,并将查询结果按`课程号升序`、`成绩降序排序`。
- 5.查询每个学生的`平均成绩`,输出学生的学号和平均成绩
- 6.查询每个学生的平均成绩,输出`平均成绩>85`的学生的学号和平均成绩
- 7.查询和林艳在同一个专业学习的`女同学`的学号与姓名。
- 8.查询比数学专业`所有`学生年龄都小的其他专业的学生的学号、姓名
- 9.查询选修了`全部课程`的学生的学号和姓名
- 10.查询选修了CS101号课程`或者`选修了CS306号课程的学生的学号
1.查询出生日期在1997~1999年
的学生的姓名和专业
方法:<值表达式> [not] between <下界> and <上界>
select sname,speciality
from studentcourse.students
where birthday between 1997 and 1999;
2.查询计算机和数学专业
的学生的学号和姓名
方法:<元组> | [not] in <子查询> :
判定一个给定的元素是否在给定的集合中
select sno,sname
from studentcourse.students
where speciality in ('计算机','数学');
3.查询姓李并且姓名只有两个汉字
的学生的学号和姓名
方法:使用通配符:
"_"(下横线)
可以与任意单个字符匹配;
"%"
可以与0个或多个任意字符匹配。
select sno,sname
from studentcourse.students
where sname like '李_ _';
一个汉字占两个字符位置,OpenGauss中一个汉字占3个字符位置。
4.查询每位学生的每门的成绩,并将查询结果按课程号升序
、成绩降序排序
。
方法:order by <排序列> [ASC | DESC];
升序ASC,降序DESC,
缺省时默认为ASC。
select *
from studentcourse.SC
order by Cno,Grade DESC
5.查询每个学生的平均成绩
,输出学生的学号和平均成绩
方法:对SC中元组按学号进行分组,平均成绩用
聚集函数AVG()
select sno,avg(grade)
from studentcourse.SC
group by Sno;
6.查询每个学生的平均成绩,输出平均成绩>85
的学生的学号和平均成绩
方法:使用HAVING短语,
WHERE语句中不能使用聚集函数
select sno,sname
from studentcourse.SC
group by Sno having arg(grade)>85;
7.查询和林艳在同一个专业学习的女同学
的学号与姓名。
方法1:对Students表设计两个
表别名s1,s2
select s2.sno,s2.sname
from studentcourse.students s1,studentcourse.students s2
where s1.speciality=s2.speciality
and s2.sname='女'
and s1.sname='林艳'
and s2.sname<>'林艳';
s2.sname<>'林艳':使查询的结果不含林艳本身。
方法2:
嵌套查询
,首先知道林艳所在的专业
select sno,sname
from studentcourse.students
where sex='女'
and s2.sname<>'林艳'
and speciality in
(select speciality
from studentcourse.students
where sname='林艳');
8.查询比数学专业所有
学生年龄都小的其他专业的学生的学号、姓名
方法:通过集合比较引出子查询
select sno,sname
from studentcourse.students
where speciality <>'数学'
and birthday> all(select birthday
from studentcourse.students
where speciality='数学');
<比较字符> all <子查询>:表示集合中数据所有进行比较
9.查询选修了全部课程
的学生的学号和姓名
方法:找到一个学生S,不存在课程 C,S没有选修 C。
双重否定表肯定。
select sno,sname
from studentcourse.students S
where not exists
(select *
from studentcourse.courses C
where not exists
(select *
from studentcourse.sc
where sc.sno=s.sno and sc.cno=c.cno
)
);
10.查询选修了CS101号课程或者
选修了CS306号课程的学生的学号
方法1:使用并运算(UNION)
交(intersect)、差(except)
select sno
from studentcourse.sc
where cno='CS101'
union
select sno
from studentcourse.sc
where cno='CS306';
集合运算自动删除重复的元组,不需用"select distinct Sno"。
方法2:使用OR(或)
select distinct Sno
from studentcourse.SC
where cno='CS101' or cno='CS306';