0
我有這樣的一個表:如何使層表平
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加一些說明,非常感謝!
我有這樣的一個表:如何使層表平
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加一些說明,非常感謝!
我發現我的這個鏈接答案: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
標籤您正在使用的數據庫管理系統。 (解決方案可能是產品特定的。)同時向我們展示您當前的查詢嘗試。 – jarlh
什麼是格言部分? 5? – Whencesoever
不知道我應該如何格式化我的SQL代碼才能更明顯。但以上是我從搜索結果中複製的代碼,它的工作原理除了從下到上,我需要的是從上到下排列。 – Jasmine