如何从oracle中的DUAL获得以下输出?

时间:2015-03-28 09:25:08

标签: sql oracle

1         L            R

1         1            1 
1         1            2
1         1            3
1         2            1
1         2            2
1         2            3
1         3            1
1         3            2
1         3            3

使用此查询但无法获取L列

Select 1,level R
from DUAL
Connect by level <=3

3 个答案:

答案 0 :(得分:5)

您可以在行生成器查询中执行笛卡尔联接,您必须生成3 rows。因此,笛卡尔积将生成总9 rows

例如,

SQL> WITH DATA AS
  2    ( SELECT LEVEL rn FROM dual CONNECT BY LEVEL <=3
  3    )
  4  SELECT 1, A.rn L, b.rn R FROM DATA A, DATA b
  5  /

         1          L          R
---------- ---------- ----------
         1          1          1
         1          1          2
         1          1          3
         1          2          1
         1          2          2
         1          2          3
         1          3          1
         1          3          2
         1          3          3

9 rows selected.

SQL>

答案 1 :(得分:2)

select 1, L, R
  from (Select level R
          from DUAL
       Connect by level <=3),
       (Select level L
          from DUAL
       Connect by level <=3)

答案 2 :(得分:1)

您可以尝试这样的事情:

SELECT 1, CEIL(lvl/3) AS l
     , ROW_NUMBER() OVER ( PARTITION BY CEIL(lvl/3) ORDER BY lvl ) AS r
  FROM (
    SELECT LEVEL AS lvl FROM dual
   CONNECT BY LEVEL <= 9
);

以上内容避免了笛卡尔联合。 See SQLFiddle here.