我有一张包含层级关系的父子节点的表格,希望按照它们之间的层级顺序排序。表格如下:
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
我该怎么做?
type = 2
如何解释4和5这样的值吗?为什么你把它们放在6之后,而不是之前?而且它们为什么有这个type
值呢,首先... - Roger Wolffiddle
吗? - A_Sk