Oracle高级查询

时间:2023-02-03 18:58:00

-- 分组查询:每个年级的学生人数

select count(1) as 人数,"GradeId" as 年级 from "Student" group by "GradeId";

select "GradeId" as 年级,"Sex" as 性别,count(1) as 人数 from "Student" group by "GradeId","Sex" ORDER BY "GradeId";

--查询每门课程的平均分,并由低到高排序

select "SubjectNo" as 课程,round(AVG("StudentResult"),2) as 平均分 from "Result" group by "SubjectNo" order by 平均分;

--having:对分组结果筛选 查询人数超过3的年级和人数

select "GradeId" as 年级, count(1) as 人数 from "Student" group by "GradeId" having count(1)>3;

--两表联查:查姓名、科目、成绩

select S."StudentName" as 姓名,R."SubjectNo" as 科目,R."StudentResult" as 成绩 from "Student" S,"Result" R --给表起别名,不要as where S."StudentNo"=R."StudentNo";

--内连接:inner join

select S."StudentName" as 姓名,R."SubjectNo" as 科目,R."StudentResult" as 成绩 from "Student" S --给表起别名,不要as inner join "Result" R on S."StudentNo"=R."StudentNo"; --on:连接

--内连接:查姓名、科目名称、成绩

select S."StudentName" as 姓名,SB."SubjectName" as 科目名称,R."StudentResult" as 成绩 from "Student" S inner join "Result" R on S."StudentNo"=R."StudentNo" inner join "Subject" SB on SB."SubjectNo"=R."SubjectNo";

--左外连接:left join

--查询所有学生的成绩

select S."StudentName" as 姓名,R."SubjectNo" as 科目,R."StudentResult" as 成绩 from "Student" S --左表,其中的行会全部查询出来 left join "Result" R --右表,如果没有跟左表匹配的信息,则用null填充 on S."StudentNo"=R."StudentNo";

--子查询:查询比李浩鑫年龄小的学生信息

--假设已经知道李浩鑫的年龄

--外层查询

select * from "Student" where "BirthDate">( select "BirthDate" from "Student" where "StudentName" ='李浩鑫' );

--查询最近一次HTML考试的最高分和最低分 3层子查询

select MAX("StudentResult") as 最高,min("StudentResult") as 最低 from "Result" where "ExamDate"=( select MAX("ExamDate") from "Result" where "SubjectNo"=( select "SubjectNo" from "Subject" where "SubjectName"='HTML' ) );

--in (值1,值2,值3....)或者 in(子查询) not in :不包含在内

--查询河南的学生

select * from "Student" where "Address" not in('河南洛阳','河南安阳','河南涧西');

--伪列:不在表中,只能查询,不能增删改

--rowid select rowid,"StudentName" as 姓名 from "Student"; select "StudentName" as 姓名 from "Student" where rowid like '%AAC'; --rownum select rownum,S."StudentName" as 姓名 from "Student" S where rownum <5;

--再MySQL中:

--limit x,y: x从哪一行开始显示(下标从0开始),y显示y条 --(m-1)*n

--查询第4-6条学生的信息

select S2."StudentName" as 姓名,S2."Phone" as 电话 from( select rownum rn,S.* from "Student" S ) S2 where S2.rn>3 and S2.rn <=6;

--oracle中分页查询 第m页,每页n条

select S2."StudentName" as 姓名,S2."Phone" as 电话 from( select rownum rn,S.* from "Student" S ) S2 --where S2.rn>(m-1)*n and S2.rn <=m*n;