从两列创建一个列表

时间:2016-08-25 15:48:16

标签: sql oracle union

in need帮助oracle SQL。

我有一张表

 from   to
 F      B
 B      R
 R      D
 E      X
 X      Q

我需要清单

F
B
R
D
E
X
Q

所以我的问题是从R - > D跳到E - > X

编辑:这是一个很大的列表,包含from和to,seperatet,另一个列为citerium。 Normaly在to列中有所有内容,所以我使用了

SELECT from,snr as Nr FROM list where StrAbsNr = 1
union all
SELECT to,snr + 1 as Nr FROM list

创建有序列表。但是在某些部分中存在间隙,在该示例中存在D - > E缺失 有人有想法吗?

2 个答案:

答案 0 :(得分:0)

select "from" as val from table
union
select to from table

如果你想保留订单:

select distinct val 
from (select "from" as val, rownum, 1 as valOrder from table
    union
    select to, rownum, 2 as valOrder from table)
order by rownum,valOrder

答案 1 :(得分:0)

为你的例子做这项工作:

WITH ft AS
  (SELECT 'f' vfrom, 'b' AS vto FROM dual  UNION ALL
  SELECT 'b' , 'r' FROM dual  UNION ALL
  SELECT 'r','d' FROM dual  UNION ALL
  SELECT 'e','x' FROM dual  UNION ALL
  SELECT 'x','q' FROM dual  )
SELECT a.a,  MAX(rn), MIN(ob)
FROM
  ( SELECT vfrom a , rownum rn, 1 ob FROM ft
  UNION ALL
  SELECT vto , rownum rn, 2 ob FROM ft
  ) a
GROUP BY a
ORDER BY MAX(rn), MIN(ob)

A    MAX(RN)    MIN(OB)
- ---------- ----------
f          1          1
b          2          1
r          3          1
d          3          2
e          4          1
x          5          1
q          5          2

 7 rows selected 

或analityc func row_number:

SELECT *
FROM
  (SELECT a.a,
    row_number() over (partition BY a order by rn, ob) rna,
    ob,
    rn
  FROM
    ( SELECT vfrom a, rownum rn, 1 ob FROM ft
    UNION ALL
    SELECT vto , rownum rn, 2 ob FROM ft
    ) a
  )
WHERE rna=1
ORDER BY rn,
  ob
A        RNA         OB         RN
- ---------- ---------- ----------
f          1          1          1
b          1          2          1
r          1          2          2
d          1          2          3
e          1          1          4
x          1          2          4
q          1          2          5

 7 rows selected