我有一张这样的表:
Child | Parent
AA |A
A |X
B |X
X |Y
Y |Z
格言部是知道的,但在每个分支的深度都是未知的
我希望它转向这样的东西:
Lv1 | Lv2 | Lv3 |lv4 | lv5
Z |Y |X |B |Null
Z |Y |X |A |AA
可以请一些人帮助,如果可以提供SQL加一些解释,高度欣赏!
答案 0 :(得分:0)
我在此链接找到了答案:https://www.sqlservercentral.com/Forums/Topic1071035-392-1.aspx
这是我改变的代码:
with cteTree
as
(
Select CID,PID,
CNAME as LV1,
cast(Null as nvarchar(100)) as LV2,
cast(Null as nvarchar(100)) as LV3,
cast(Null as nvarchar(100)) as LV4,
cast(Null as nvarchar(100)) as LV5,
cast(Null as nvarchar(100)) as LV6,
cast(Null as nvarchar(100)) as LV7,
cast(Null as nvarchar(100)) as LV8,
cast(Null as nvarchar(100)) as LV9,
cast(Null as nvarchar(100)) as LV10,
cast(Null as nvarchar(100)) as LV11,
0 as Level
from PSFT_DEPT_TREE
where PID = 0
union all
Select Child.CID,
Child.PID,
LV1,
case when Level+1 = 1 then CNAME else LV2 end,
case when Level+1 = 2 then CNAME else LV3 end,
case when Level+1 = 3 then CNAME else LV4 end,
case when Level+1 = 4 then CNAME else LV5 end,
case when Level+1 = 5 then CNAME else LV6 end,
case when Level+1 = 6 then CNAME else LV7 end,
case when Level+1 = 7 then CNAME else LV8 end,
case when Level+1 = 8 then CNAME else LV9 end,
case when Level+1 = 9 then CNAME else LV10 end,
case when Level+1 = 10 then CNAME else LV11 end,
Level+1
from CteTree
join PSFT_DEPT_TREE child
on child.PID = CteTree.CID
)
select * from cteTree