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

时间:2016-06-21 11:36:56

标签: sql sql-server sql-server-2008 recursion common-table-expression

我有一个返回父子关系的CTE。如果我使用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

返回

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

1 个答案:

答案 0 :(得分: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