我有表與分層,父子關係,並希望按該層次結構排序。表是:如何按層次結構排序
id|parent|type
--------------
1 |0 |1
2 |0 |1
3 |0 |1
4 |0 |2
5 |0 |2
6 |2 |2
7 |3 |2
而作爲結果,我想這一點:
id|parent|type
--------------
1 |0 |1
2 |0 |1
6 |2 |2
3 |0 |1
7 |3 |2
4 |0 |2
5 |0 |2
所以我希望得到的東西像一個樹視圖,其中1型排列第一,在最後2型。
現在我試圖使用遞歸,但順序是錯誤的:
with cte as
(
select id, parent, type from tbl where id=1
union all
select id, parent, type,
ROW_NUMBER()over(
order by
(case when t.type = 1 then 1
when t.type = 2 then 2
else 1000
end) as rn
from tbl t
inner join cte c on c.id=t.parent
)
select * from cte
order by rn
我怎樣才能做到這一點?
連接方式是你最好的朋友,如果你想讓這樣的樹像代表http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm – istovatis
@istovatis那真的很酷,但我正在使用MS Sql服務器 – Gleb
你能解釋'type = 2'應該如何解釋像4和5這樣的值嗎?例如,爲什麼你把它們放在6之後,而不是之前?爲什麼他們有這個'類型'的價值,首先... –