我有一个带有先前id的表,并希望根据id_prev对输出进行排序。 Null必须是第一个值。
表格
id | id_prev | data
------------------
1 | 2 | foo
2 | 4 | foo
3 | 1 | foobar
4 | null | fooo
10 | 3 | fo
8 | 10 | fo
结果
id | id_prev | sort | data
------------------
4 | null | 1 | fooo
2 | 4 | 2 | foo
1 | 2 | 3 | foo
3 | 1 | 4 | foobar
10 | 3 | 5 | fo
8 | 10 | 6 | fo
答案 0 :(得分:2)
试试这个:
select * from (
select
t.id,
t.id_prev,
t.data,
row_number() over(order by t.id_prev DESC NULLS FIRST) AS sort
from
{your_table} t
) t order by t.sort;
答案 1 :(得分:1)
先前连接
select id,id_prev,level,data
from TABLE_NAME
start with id_prev is null
connect by prior id=id_prev
order by level;
答案 2 :(得分:0)
试试这个Order by
Order by case when id_prev is null then 1 else 0 end desc,id_prev desc
如果你想在结果中排序列
Row_number()
Over(Order by case when id_prev is null then 1 else 0 end desc,id_prev desc) as Sort