SQL Server CTE:如何仅选择最低级别

时间:2017-04-10 22:57:45

标签: sql-server-2016

我想只选择/显示最低级别的CTE。请帮忙。我正在使用SQL Server 2016。

Create Table Location 
(
    Id int
    Name varchar(20)
    Parent int 
)

Insert into location 
values (1, Location1, null), (2, Location1child, 1), 
       (3, Location1grandchild, 2), (4, Location2, null),
       (5, Location3, null), (6, Locationchild3, 5)

我只需要显示最低级别的记录3,4,6。

更新:我已经创建了查询,但没有显示记录号4。我期待显示4号记录,因为记录是该组中的最低级别。

With CTE (id, cte_level, cte_name, cte_longname) as 
(
    Select 
        A.ID, 1, 
        cast(A.name as varchar(max)),
        cast(A.name as varchar(max))
    from 
        Location A

    Union All

    Select 
        A.ID, cte_level + 1,
        replicate(' · ' , cte_level ) + cast(A.name as varchar(max)),
        cte.cte_longname + ' . ' +  cast(A.name as varchar(max))
    from 
        Location A
    inner join 
        CTE ON A.Parent = CTE.id
)
select 
    CTE_2.id, 
    CTE_2.cte_longname [name]
    --, A.cte_name [name]           
  from 
      CTE as CTE_1 
inner join 
    CTE as CTE_2 on CTE_1.id = cte_2.id
where 
    CTE_1.cte_level  = 1 
    And CTE_2.cte_level = (Select MAX(CTE.cte_level) From CTE)
order by 
    cte_2.cte_longname 

1 个答案:

答案 0 :(得分:0)

与CTE无关。只需使用LEFT OUTER JOIN进行IS NULL检查。

SELECT P.*
FROM Location P
LEFT OUTER JOIN Location C ON P.Id = C.Parent
WHERE C.Id IS NULL;