SQL 获取活动父代的所有父代和子代

问题描述 投票:0回答:1

下面是我的案例,我有一个像.NET的表结构,我只想得到所有活跃的父母(即名字为A,E和G的记录)和他们的孩子。

enter image description here

我只想得到所有活跃的父母(即名字为A、E和G的记录)和他们的孩子。

预期的结果应该是这样的。

enter image description here

sql sql-server sql-server-2008 recursive-query
1个回答
0
投票
with recursive as (
SELECT      par.Id, 
            par.Name, 
            par.ParentID, 
            par.IsDeleted  
FROM        table1 par 
JOIN  table1 chi 
  ON        par.Id = chi.ParentId  

union all 

SELECT      par.Id, 
            par.Name, 
            par.ParentID, 
            rec.IsDeleted  
FROM        table1 par 
JOIN  recursive rec 
  ON        rec.Id = par.ParentId  
),

check_tbl as (
       select Id,
       sum(IsDeleted) as IsDeleted
from recursive
group by Id
having sum(IsDeleted)=0
)

select table1.id, Name, ParentID, table1.IsDeleted
from check_tbl join table1 on table1.Id=check_tbl.Id
;
© www.soinside.com 2019 - 2024. All rights reserved.