我为学生提供以下3个表格,我需要找到当前正在同时开会的班级中报名的学生的姓名
student(**snum**, sname, major, level, age)
class(**cname**, meets_at, room)
enroll(**snum**, **cname**)
每个表的键都以粗体显示。
我已经尝试过以下代码,但不确定在这里是否接近正确答案。
select s.sname
from student s
join
( select c.cname
, c.meets_at
, (count(*)
from class c
having count( * ) > 1
) e
on c.cname = e.cname
and s.snum = e.snum;
答案 0 :(得分:0)
我认为这与meetsat
的学生一起加入。因此,这可以让学生掌握上课时间:
select s.sname, c.meets_at
from students s join
enrolls e
on s.snum = e.snum join
classes c
on c.cname = e.cname;
然后,要获取重复项,请使用汇总并使用having
进行过滤:
select s.snum, s.sname, c.meets_at, count(*) as cnt
from students s join
enrolls e
on s.snum = e.snum join
classes c
on c.cname = e.cname
group by s.snum, sname, c.meets_at
having count(*) >= 2;
请注意,这包括ID和姓名,因为两个学生可能具有相同的姓名。
最后,一个学生可以有多对冲突的班级,但是您只想见一次学生。尽管以上内容可能足以满足您的需求,但针对上述问题的更准确解决方案是:
select distinct s.sname
from students s join
enrolls e
on s.snum = e.snum join
classes c
on c.cname = e.cname
group by s.snum, sname, c.meets_at
having count(*) >= 2;
答案 1 :(得分:0)
select s.snum, s.sname, c.meets_at ,count(*) as cnt into #tempStudents
from students s
join enrolls e on s.snum = e.snum
join classes c on c.cname = e.cname;
将整个数据放入临时表
select sname from #tempStudents
group by snum,sname ,meets_at
having cnt >=2
现在在临时表上应用过滤以获取需求数据 以及如果您需要学生的不同姓名,请在姓名前放置 Distinct 关键字。