我有一個表以下簡化信息被稱爲套房,不幸的是我無法控制的SQL多個自聯接的列
id title parentsuiteid
1 test NULL
4 pay1 3
5 pay2 3
3 Bill Payments 2
14 Vouchers 2
15 Mini 2
2 Site Tests NULL
我想有一個水平表示使用報告如
test
Site tests Bill Payments pay1
Site tests Bill Payments pay2
Site tests Vouchers
Site tests Mini
我是用加入
select a.id,a.title,b.title,a.parentsuiteid from #temp2 a
left outer join #temp2 b
on a.id = b.parentsuiteid
id title title parentsuiteid
1 test NULL NULL
4 pay1 NULL 3
5 pay2 NULL 3
3 Bill Payments pay1 2
3 Bill Payments pay2 2
14 Vouchers NULL 2
15 Mini NULL 2
2 Site Tests Bill Payments NULL
2 Site Tests Vouchers NULL
2 Site Tests Mini NULL
這個工程有兩個LEVE測試LS罰款,但我不能預測有多少水平,將來還會有,它似乎變得複雜起來有兩個以上
如何讓我的輸出看起來像+水平表示 - 5級?
究竟什麼是你的問題? – maryjane
編輯問題 – user2168435
如果你有N個級別,那麼你需要一個遞歸的SQL查詢,也稱爲CTE。請參閱http://stackoverflow.com/questions/1757260/simplest-way-to-do-a-recursive-self-join-in-sql-server – jhilden