我正在尝试使用以下示例数据在 SQL Server 中执行递归 CTE
Class Student
------ ------
English Sally <- Sally is what were searching for
English Peter <- Peter's on same Class as Sally
Swedish Peter <- Found because Peter's on this class
Dutch Peter <- Found because Peter's on this class
Finnish Harry <- Not found, no relation to class or student
Swedish Tim <- Found because Peter's on Swedish class
Spanish Lauren <- Not found, no relation to class or student
Spanish Colin <- Not found, no relation to class or student
所以我需要一个 CTE,我将“Sally”作为参数,它会找出与 Sally 相关的所有不同班级,然后是与 Sally 所在班级相关的所有学生,然后是与同一班级的学生相关的所有班级Sally,依此类推,直到找不到更多行。
但我只是不知道如何编写连接,这是我尝试过的,但惨遭失败:
WITH myCTE (Class, Student) AS
(
SELECT Class, Student FROM TABLE1 WHERE TABLE1.Student= 'Sally'
UNION ALL
SELECT t.Class, t.Student FROM TABLE1 t
JOIN myCTE t2 ON t2.Class = t.Class
)
SELECT * FROM myCTE