2016-11-16 45 views
1

我已經在這個格式找到所有成員在樹結構

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 

我想找到所有的StatementAreaIds在最終母公司主題是繼承樹型表,說數學(即SubjectId = 110)。舉例來說,如果SubjectId是數學我會得到樹StatementAreaIds的列表:

StatementAreaId 
--------------- 
2 
3 
4 
5 
6 

樹的最大深度爲3,如果沒有什麼幫助。

感謝

+0

預期輸出應該是.. – Chanukya

+0

例如,如果SubjectId是數學,我會得到樹中StatementAreaIds的列表,例如, 2,3,4,5,6 –

+0

請在你的問題中正確地發佈要求.. – Chanukya

回答

2

遞歸CTE救援:

創建和填充示例表:(保存我們這一步在你未來的問題)

DECLARE @T AS TABLE 
(
    StatementAreaId int, 
    ParentStatementAreaId int, 
    SubjectId int, 
    Description varchar(20) 
) 

INSERT INTO @T VALUES 
(1    , 0      , 100  , 'Reading'), 
(2    , 0      , 110  , 'Maths'), 
(3    , 2      , 0   , 'Number'), 
(4    , 2      , 0   , 'Shape'), 
(5    , 3      , 0   , 'Addition'), 
(6    , 3      , 0   , 'Subtraction') 

查詢:

;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