我正在努力解决如何在MSSQL中完成以下查询的逻辑。
我如何返回两名学生和他们一起参加的任何课程的清单? E.g。
+-----------+------------+------------+
|Student1 | Student2 | Class Name |
+-----------+------------+------------+
|John Smith | Jane Doe | Trig |
+-----------+------------+------------+
|John Smith | Jane Smith | Math |
+-----------+------------+------------+
答案 0 :(得分:3)
您可以使用自我加入来执行此操作:
select c1.student, c2.student, c1.class
from ClassStudents c1 join
ClassStudents c2
on c1.class = c2.class and
c1.student < c2.student;
如果两名学生一起上过多个班级,每个班级将返回一行。
如果你在表中使用id
而不是名字(一个好主意),那么你需要从其他表中加入适当的信息。我会把它留给你。
编辑:
要计算两个学生一起上课的次数,您可以使用group by
:
select c1.student, c2.student, count(*) as NumClasses
from ClassStudents c1 join
ClassStudents c2
on c1.class = c2.class and
c1.student < c2.student
group by c1.student, c2.student;
您可以使用having
子句按count(*)
进行过滤。您可以将其连接回其他表以获取特定类。
以下是如何将其加入原始表格的方法:
select s1.name as student1, s2.name as student2, count(*) as NumClasses
from ClassStudents c1 join
ClassStudents c2
on c1.class = c2.class and
c1.studentid < c2.studentid join
Students s1
on c1.studentid = s1.studentid join
Students s2
on c2.studentid = s2.studentid
group by c1.name, c2.name
having count(*) > 1;
您也可以将此作为子查询执行,但这很容易。
答案 1 :(得分:0)
为每个学生创建列表很容易,Merge使用WHEN MATCHED THEN
例如:让学生A参加SAC1
和SAC2
参加学生B课程的课程
MERGE SAC1 AS target
USING SAC2 AS source
ON (target.class = source.class)
WHEN MATCHED THEN
--insert into result table
如果您想要参加同一课程的所有学生的名单,请执行此操作
MERGE studentClasses AS target
USING studentClasses AS source
ON ((target.class = source.class) AND (target.studentId <> source.studentId))
WHEN MATCHED THEN
--insert into result table