如何此表中的Oracle9排序:
START | END | VALUE
A | F | 1
D | H | 9
F | C | 8
C | D | 12
为了让这个样子?:
START | END | VALUE
A | F | 1
F | C | 12
C | D | 8
D | H | 9
目标是开始每下一行与上一行结束。
这不能与ORDER BY子句独自完成,因为它必须先找到没有前辈的纪录,然后寻找下一个记录进行结束和开始的两个记录栏等,这是你需要一个反复的过程递归查询。
递归查询将查找第一个记录,那么接下来等等,给他们的序列号。然后你会被那些生成的数字使用结果和秩序。
这里是如何做到这一点的标准SQL。这是从的Oracle 11g支持开始而已,但是。在Oracle 9,你将不得不使用与我不熟悉CONNECT BY
。希望你或其他人可以转换查询您:
with chain(startkey, endkey, value, pos) as
(
select startkey, endkey, value, 1 as pos
from mytable
where not exists (select * from mytable prev where prev.endkey = mytable.startkey)
union all
select mytable.startkey, mytable.endkey, mytable.value, chain.pos + 1 as pos
from chain
join mytable on mytable.startkey = chain.endkey
)
select startkey, endkey, value
from chain
order by pos;
更新:正如你所说的数据是循环的,你必须改变上面的查询,从而开始一个任意选定的行和停止通过时:
with chain(startkey, endkey, value, pos) as
(
select startkey, endkey, value, 1 as pos
from mytable
where rownum = 1
union all
select mytable.startkey, mytable.endkey, mytable.value, chain.pos + 1 as pos
from chain
join mytable on mytable.startkey = chain.endkey
)
cycle startkey set cycle to 1 default 0
select startkey, endkey, value
from chain
where cycle = 0
order by pos;