SQL基于2列排序随机行

时间:2016-01-14 11:18:53

标签: sql sql-order-by oracle9i

如何在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

目标是从上一行的结尾开始每一行。

1 个答案:

答案 0 :(得分:0)

单独使用order by子句不能这样做,因为它必须首先找到没有前任的记录,然后找到比较两个记录的end和start列的下一条记录等。这是一个迭代过程,你需要一个递归查询。

递归查询会找到第一条记录,然后是下一条记录,依此类推,给出序列号。然后,您将使用结果并按生成的数字排序。

以下是如何在标准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;