我有以下示例数据:
==================================
id name parent isactive
=================================
001 alfa null 1
002 beta 001 0
003 carlie 001 1
004 daniel 002 1
005 echo 001 1
从这个示例数据中,我想输出以下数据:
=====
name
=====
alfa
carlie
echo
以下条件应适用:
parent = null AND isactive = 1
parent != null AND isactive = 1 AND parent_record.isactive = 1
因此父记录和子记录都应该有isactive = 1
,其中有查找。
答案 0 :(得分:1)
试试这个:
;with cte as
(select *, 0 as level from tbl
where parent is null and isactive = 1
union all
select t.*, level + 1
from cte c
inner join tbl t on c.id = t.parent and t.isactive = 1)
select id, name, parent, isactive
from cte
递归CTE用于解决此问题。在顶层,我们选择没有父母且活跃的记录。对于所有其他级别,我们检查他们是否有父级并且他们是活动的。