这是完成输出的一种方法,使用递归 CTE 硬编码来填充多达 9 级的层次结构(您需要根据需要将表/列引用更改为真实对象名称,并且您可能需要varchar(50)
如果列的实际类型name
比这更宽,则增加):
with cte as (
select id, 1 as level,
name as level1,
cast(null as varchar(50)) as level2,
cast(null as varchar(50)) as level3,
cast(null as varchar(50)) as level4,
cast(null as varchar(50)) as level5,
cast(null as varchar(50)) as level6,
cast(null as varchar(50)) as level7,
cast(null as varchar(50)) as level8,
cast(null as varchar(50)) as level9
from table1 t
where parentid is null
union all
select t.id, cte.level + 1 as level,
case when level = 0 then t.name else cte.level1 end as level1,
case when level = 1 then t.name else cte.level2 end as level2,
case when level = 2 then t.name else cte.level3 end as level3,
case when level = 3 then t.name else cte.level4 end as level4,
case when level = 4 then t.name else cte.level5 end as level5,
case when level = 5 then t.name else cte.level6 end as level6,
case when level = 6 then t.name else cte.level7 end as level7,
case when level = 7 then t.name else cte.level8 end as level8,
case when level = 8 then t.name else cte.level9 end as level9
from table1 t
inner join cte on cte.id = t.parentid
)
select * from cte;
样本输出:
| ID | LEVEL | LEVEL1 | LEVEL2 | LEVEL3 | LEVEL4 | LEVEL5 | LEVEL6 | LEVEL7 | LEVEL8 | LEVEL9 |
----------------------------------------------------------------------------------------------------
| 1 | 1 | TopLevel | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| 2 | 2 | TopLevel | Region 1 | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| 3 | 3 | TopLevel | Region 1 | Fleet 1 | (null) | (null) | (null) | (null) | (null) | (null) |
| 4 | 3 | TopLevel | Region 1 | Fleet 2 | (null) | (null) | (null) | (null) | (null) | (null) |
演示:http ://www.sqlfiddle.com/#!6/0bd5d/14