Sql 查找树结构中的所有成员
我以这种格式继承了一个树型表Sql 查找树结构中的所有成员,sql,sql-server,Sql,Sql Server,我以这种格式继承了一个树型表 StatementAreaId | ParentStatementAreaId | SubjectId | Description ----------------------------------------------------------------- 1 | 0 | 100 | Reading 2 | 0 |
StatementAreaId | ParentStatementAreaId | SubjectId | Description
-----------------------------------------------------------------
1 | 0 | 100 | Reading
2 | 0 | 110 | Maths
3 | 2 | 0 | Number
4 | 2 | 0 | Shape
5 | 3 | 0 | Addition
6 | 3 | 0 | Subtraction
我想找到所有最终父科目所在的StatementAreaID,比如数学(即SubjectId=110)。例如,如果主题是数学,我将在树中获得StatementAreaID列表:
StatementAreaId
---------------
2
3
4
5
6
如果有帮助,树的最大深度为3
感谢CTE的救援: 创建并填充示例表:(请在以后的问题中保存此步骤) 查询:
;WITH CTE AS
(
SELECT StatementAreaId, ParentStatementAreaId
FROM @T
WHERE SubjectId = 110
UNION ALL
SELECT t1.StatementAreaId, t1.ParentStatementAreaId
FROM @T t1
INNER JOIN CTE ON t1.ParentStatementAreaId = CTE.StatementAreaId
)
SELECT StatementAreaId
FROM CTE
结果:
StatementAreaId
2
3
4
5
6
预期输出应该是..例如,如果主题是数学,我会在树中得到一个StatementAreaID列表,例如2,3,4,5,6请在问题中正确地发布要求..以各种方式向我们展示预期结果
StatementAreaId
2
3
4
5
6