各階層を平坦化するようなすべてのシリーズを出力できるように階層を作成する SQL Server CTE の例を探しています。たとえば、家系図で、祖父母からルートが始まる場合、各家族のメンバーの階層リストのリストと、メンバーの詳細+親の行の詳細が必要です
child1 row child1 +Parent row child1 + Grand parent Row child2 Row child2 + parent row child2 + grand parent's row and so on
CREATE TABLE Family(id int NULL,
Name varchar(20) null, Parent_id int NULL, level int NULL )
INSERT INTO Family VALUES
(1, 'Grand Parent',NULL, 1),
(2, 'Parent' , 1, 2),
(3, 'Child1' , 2, 3),
(4, 'Child2' , 2, 3)
select * from Family;
id Name Parent_id level
1 Grand Parent NULL 1
2 Parent 1 2
3 Child1 2 3
4 Child2 2 3
これが私が現時点でできることです。親行の詳細は、5 列目と 6 列目にあります。
with cte as
(
select ID,Parent_id,level,Name,id as parent_id,level, 'a' as type
from family
--where ID=3
union all
select f.ID,f.Parent_id,f.level,f.Name,c.id as parent_id,c.level, 'r' as type
from family f
inner join cte c
on f.parent_id=c.id
)
select * from cte order by id
これが結果のはずです。(列 5 と 6 に注意)
Child_ID Parent_id Child_level Name parent_id level
1 NULL 1 Grand Parent 1 1
2 1 2 Parent 2 2
2 1 2 Parent 1 1
3 2 3 Child1 1 1
3 2 3 Child1 2 2
3 2 3 Child1 3 3
4 2 3 Child2 4 3
4 2 3 Child2 2 2
4 2 3 Child2 1 1
前もって感謝します。