聚沙成塔

数据库常用查询语句(Oracle)【转】

上一篇 / 下一篇  2014-09-20 09:55:06 / 个人分类:数据库

数据库的联合子查询在测试中经常会用到。发现了一篇很好的范例,原文由liaoxj发布,http://www.51testing.com/html/95/13795-866766.html

1 建表语句
create table SC
(
  CNO   NUMBER,//课程号
  SNO   NUMBER,//学员号
  GRADE NUMBER//得分
)

create table STUDENT
(
  SNO   NUMBER not null,//学员号
  SNAME VARCHAR2(40),//学生姓名
  SAGE  NUMBER,//年龄
  SSEX  VARCHAR2(10)//性别
)

create table COURSE
(
  CNO     NUMBER,//课程号
  CNAME   VARCHAR2(40),课程名
  CPNO    NUMBER,
  CCREDIT NUMBER,学分
  TEACHER VARCHAR2(20)老师
)

2  部分一
1.      查询‘陈东’老师教授的课程和课程号
select cno,cname from course where teacher='陈东';//注意是单引号
2.      查询年纪大于23岁的男生信息
select * from student where ssex='男' and sage >23
3.      查询至少选修‘陈东’老师的一门课程的女生
Select sname from student where Ssex='女'and sno in(select sno from sc where cno in(select cno from course where teacher='陈东'))

3  部分二
1.      统计所有学生选修的课程门数
select count(distinct(cno)) from sc
2.      统计每门课程选修的人数
select count(sno) as 选修数,cno as 课程号 from sc group by cno
3.      求‘陈东’老师所教授的每门课程的平均成绩和总人数
select count(sc.cno),sc.cno,avg(sc.grade) from sc,course where sc.cno=course.cno and course.teacher='陈东' group by sc.cno
4.      统计选修课程2的同学的平均成绩
select avg(grade) from sc where cno=2
5.      统计每门课程的学生人数(要求超过2人才统计)要求输出课程号和选修人数,结果按照人数的降序排序,人数相同的话按照课程号升序排序
Select cno,count(sno)from SC group by cno having count(sno)>2 order by 2 desc, 1
6.      查询姓名以朱开头的所有学生
select * from student where sname like '朱%'
7.      找出年纪大于女生平均年纪的男生
select * from student where Ssex='男' and Sage>(select avg(Sage) from student where Ssex='女')
8. 找出在SC表没有成绩,但是在Student中存在的学生
select * from student where sno not in(select sno from sc ) and  sno in(select sno from sc where grade is null)

4 部分三:
1. 查询选修总学分在10学分以下的学生姓名
select sc.sno,sum(course.ccredit) from sc,course where sc.cno=course.cno group by sc.sno having sum(course.ccredit)<10//sum求和,count统计记录数

TAG: Oracle oracle

 

评分:0

我来说两句

Open Toolbar