【SQL】SQL高级查询

student表
在这里插入图片描述
take表

在这里插入图片描述

  • 查询只选了CS112课程,而没有选其他课程的学生信息;
select s.*
 from student s, take t
 where s.sno = t.sno
 and s.sno not in ( select sno
 from take
 where cno != 'CS112' )
  • 使用聚合函数 COUNT 判断哪些学生最多选修了两门课程
 from student s, take t
where s.sno = t.sno
group by s.sno,s.sname,s.age
having count(*) <= 2
  • 找出年龄最多大于其他两名同学的学生
select s1.* from student s1
where 2>=(
	select count(*) from student s2
	where s1.age>s2.age)

使用窗口函数 DENSE_RANK 找出比其他 0 个、1 个或 2 个学生年龄大的学生。

select sno,sname,age
from (
	select sno,sname,age,
	dense_rank()over(order by age) as dr
	 from student) x
where dr <= 3
  • 至少选修了两门课程的学生。
select s.sno,s.sname,s.age
from student s, take t
where s.sno = t.sno
group by s.sno,s.sname,s.age
having count(*) >= 2

使用窗口函数 COUNT OVER 筛选出至少选修了两门课程的学生。

select distinct sno,sname,age
from (
	select s.sno,s.sname,s.age,
	count(*) over (
	partition by s.sno,s.sname,s.age
 ) as cnt
from student s, take t
where s.sno = t.sno 
 x
where cnt >= 2
  • 使用聚合函数 MIN 和 MAX 找出同时选修了 CS112 和 CS114 课程的学生。
select s.sno, s.sname, s.age
from student s, take t
where s.sno = t.sno
and t.cno in ('CS114','CS112')
group by s.sno, s.sname, s.age6 
having min(t.cno) != max(t.cno)

teach表
在这里插入图片描述

professor表
在这里插入图片描述

  • 找出只讲授一门课程的教授
select p.lname,p.dept,p.salary,p.age
from professor p, teach t
where p.lname = t.lname
group by p.lname,p.dept,p.salary,p.age
having count(*) = 1
  • 找出选修了全部课程的学生
select s.sno,s.sname,s.age
from student s, take t
where s.sno = t.sno
group by s.sno,s.sname,s.age
having count(t.cno) = (select count(*) from courses)
  • 找出比任何其他学生年龄都大的学生
select *
from student
where age = (select max(age) from student)

在内嵌视图中使用窗口函数 MAX OVER 找出年龄最大的学生。

select sno,sname,age
from (
select s.*,
max(s.age)over() as oldest 
from student s
x
where age = oldest

EMP表
在这里插入图片描述

  • 返回奇数行员工姓名
select ename
from (
select row_number() over (order by ename) rn,
ename
from emp
) x
where mod(rn,2) = 1

mysql

select x.ename
from (
select a.ename,
	(select count(*)
	from emp b
	where b.ename <= a.ename) as rn
	from emp a ) x
where mod(x.rn,2) = 1
  • 返回 5 个工资最高的员工的姓名和工资
select ename,sal
from (
	select ename, sal,
	dense_rank() over (order by sal desc) dr 
	from emp 
) x 
where dr <= 5
select ename,sal
from (
	select (select count(distinct b.sal)
	from emp b
	where a.sal <= b.sal) as rnk,
	a.sal,
	a.ename
	from emp a
)
where rnk <= 5
  • EMP 表中工资最高和最低的员工
select ename
from emp
where sal in ( (select min(sal) from emp),
(select max(sal) from emp) )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值