SQL 查找子行相对于顶部父行的深度

SQL Find depth of child row relative to top parent row

我有一个 returns 亲子关系的 CTE。如果我 select 使用 PanelID 的 where 子句,我会得到子面板的所有父级。然而,深度是相反的。我需要子面板的部门为 2,顶级父面板为 0。

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

Return

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

显而易见的解决方案是将查询包装在子查询中并使用 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