SQL Server:如何仅获取树的最新(最深)节点

时间:2018-10-06 07:18:01

标签: sql sql-server tree

如果节点具有子元素,则不要选择该节点,否则返回此节点:

这是我的查询,该查询返回具有级别列的所有行:

 WITH AnalysisTree(Oid, 
              Name, 
              Parent, 
              Level)
 AS (SELECT a.Oid, 
            a.Name, 
            a.ParentAnalysis Parent, 
            0 AS Level
     FROM Analysis a
     WHERE a.GCRecord IS NULL
           AND a.ParentAnalysis IS NULL
     UNION ALL
     SELECT a2.Oid, 
            a2.Name, 
            a2.ParentAnalysis Parent, 
            AnalysisTree.level + 1 level
     FROM Analysis a2
          INNER JOIN AnalysisTree ON AnalysisTree.Oid = a2.ParentAnalysis
     WHERE a2.GCRecord IS NULL)
 SELECT *
 FROM AnalysisTree atr;

1 个答案:

答案 0 :(得分:2)

select * 
from AnalysisTree 
where Oid not in (select ParentAnalysis from Analysis where ParentAnalysis is not null)