3

我有一個返回父子關係的CTE。如果我使用PanelID選擇where子句,則獲取子面板的所有父母。但是,深度是相反的。我需要的子面板的部門是2和頂父爲0SQL查找子行相對於頂級父行的深度

WITH category_cte AS 
(SELECT PanelID AS SourceID, PanelID, BP_DP, 0 AS depth FROM dbo.tblPanels 
        UNION ALL 
SELECT CTE.SourceID, C.PanelID, C.BP_DP, CTE.depth + 1 AS depth 
      FROM dbo.tblPanels AS C INNER JOIN 
       category_cte AS CTE ON C.SCID = CTE.PanelID) 
     SELECT  SourceID, PanelID, BP_DP, depth 
     FROM   category_cte AS category_cte_1 where PanelID = x 

返回

SourceID PanelID BP_DP depth 
1240   1240  1  0 
1446   1240  1  1 
1434   1240  1  2 
+0

這不是什麼回報?遞歸地使用具有計算深度的CTE應當將頂部節點返回爲0,並且隨後的節點爲> 0。因此,如果我們有祖父母 - 子 - 父 - 孩子,它將出現0-1-2。 – BlackjacketMack

+0

返回給孩子的值爲0。我正在尋找相反的東西。 – user1781272

回答

1

顯而易見的解決方案是包裝您的查詢在子查詢和使用ROW_NUMBER計算depth按降序排列:

WITH category_cte AS 
(SELECT PanelID AS SourceID, PanelID, BP_DP, 0 AS depth 
FROM dbo.tblPanels 

UNION ALL 

SELECT CTE.SourceID, C.PanelID, C.BP_DP, CTE.depth + 1 AS depth 
FROM dbo.tblPanels AS C 
INNER JOIN category_cte AS CTE ON C.SCID = CTE.PanelID)  
SELECT SourceID, PanelID, BP_DP, 
     ROW_NUMBER() OVER (ORDER BY depth DESC) -1 AS depth 
FROM (
    SELECT SourceID, PanelID, BP_DP, depth 
    FROM category_cte AS category_cte_1 
    where PanelID = x) AS t