查询以找到一起上过许多课程的学生

时间:2019-11-21 11:00:43

标签: sql sql-server

如何编写查询以查找所有同时修过许多课程的学生。

表架构:

  • Student:ID int,Fname nvarchar(50),Lname nvarchar(50)
  • Course:Course_ID int,名称为nvarchar(100),创建日期为日期时间
  • Enrollment:Student_ID int,Course_id int

例如:我想看看一起修读三门以上课程的学生。

我想要这样的结果:

Course.name, Student.fname, student.lname
CSC 201,        Jhon ,         Khal
CSC 201,        Mike,          Alan
CSC 201,        Peter,         Wick
IS 220,         Jhon ,         Khal
IS 220,         Mike,          Alan
IS 220,         Peter,         Wick
.               Jhon ,         Khal
.               Mike,          Alan
.               Peter,         Wick
.
.
.
.

这是我想出的:

select Course.name, Student.fname, student.lname  from enrollment e
join course c on c.course.Id = e.course.Id
join student s on s.id = e.student_ID

3 个答案:

答案 0 :(得分:1)

  

如何编写查询以查找所有一起学习了许多课程的学生。

我将使用聚合和having。对于三门任意课程:

select s.id, s.fname, s.lname 
from student s join
     enrollment e
     on s.id = e.student_ID 
group by s.id, s.fname, s.lname 
having count(*) >= 3;

请注意,不需要courses表。 enrollment有足够的信息。这不是 返回有关课程的信息-因为您的问题只是要求符合条件的学生

如果您想看课程,那么string_agg()是将值放在一行的最简单的解决方案:

select s.id, s.fname, s.lname,
       string_agg(c.name, ', ') as courses
from student s join
     enrollment e
     on s.id = e.student_ID join
     course c
     on c.course.Id = e.course.Id
group by s.id, s.fname, s.lname 
having count(*) >= 3;

请注意,string_agg()是SQL Server的最新版本,因此在您的版本中可能不可用。

答案 1 :(得分:0)

在以下脚本中尝试此操作-

SELECT C.Name course_name, 
A.fname,
A.lname
FROM Student A
INNER JOIN Enrollment B ON A.ID = B.Student_ID
INNER JOIN Course C ON B.Course_id = C.Course_id
WHERE A.ID IN
( 
    SELECT Student_ID  
    FROM Enrollment
    GROUP BY Student_ID  
    HAVING COUNT(*) >= 3 
) 

答案 2 :(得分:0)

以下内容不会赢得任何性能奖章,但会产生请求的输出结果:

WITH cte AS (
    SELECT s1.name AS studentname1
         , s2.name AS studentname2
         , c.name AS coursename
         , COUNT(*) OVER (PARTITION BY s1.id, s2.id) AS sharecount
    FROM course c
    JOIN enrollment AS e1 ON c.id = e1.course_id
    JOIN enrollment AS e2 ON c.id = e2.course_id AND e1.student_id < e2.student_id
    JOIN student    AS s1 ON e1.student_id = s1.id
    JOIN student    AS s2 ON e2.student_id = s2.id
)
SELECT *
FROM cte
WHERE sharecount >= 3
ORDER BY studentname1, studentname2, coursename

基本上,它与自己的入学表连接,以查找同一课程中所有已注册的学生对,并使用COUNT(*) OVER ()来计算学生对的数量。