如何在oracle中组合2个select语句

时间:2016-10-08 21:43:24

标签: oracle

我有表test2.it包含

ID

    1
    4
    5
   10 

现在我发现此序列中缺少数字。使用此查询

SELECT min_ID - 1 + level mn FROM 
( SELECT MIN(ID) min_ID , MAX(ID) max_ID FROM test2 ) 
CONNECT BY level <= max_ID - min_ID + 1 minus SELECT ID FROM test2

输出是:

MN
---   
2   
3   
6   
7   
8   
9

现在我想结合这两个列。我无法做到这一点请帮助我。 我希望输出像

  1        2
  4        3
  7        5
  10       6
           8
           9

1 个答案:

答案 0 :(得分:1)

Oracle安装程序

CREATE TABLE test2 (id) AS
SELECT  1 FROM DUAL UNION ALL
SELECT  4 FROM DUAL UNION ALL
SELECT  5 FROM DUAL UNION ALL
SELECT 10 FROM DUAL;

<强>查询

WITH bounds ( mn, mx ) AS (
  SELECT MIN( id ), MAX( id ) FROM test2
),
missing (id, rn) AS (
  SELECT id, ROWNUM
  FROM   (
    SELECT mn + LEVEL AS id
    FROM   bounds
    CONNECT BY LEVEL < MX - MN
    MINUS
    SELECT id
    FROM   test2
  )
),
existing ( id, rn ) AS (
  SELECT id, ROWNUM
  FROM   test2
)
SELECT e.id, m.id
FROM   existing e
       FULL OUTER JOIN
       missing m
       ON ( e.rn = m.rn );

<强>输出

        ID         ID
---------- ----------
         1          2 
         4          3 
         5          6 
        10          7 
                    9 
                    8