Oracle SQL:用于生成特定序列的分层查询

时间:2013-06-13 12:28:18

标签: plsql oracle11g

目前我有这样的事情:

SELECT TO_CHAR(ROWNUM, '009'), TO_CHAR(L, '009')
  FROM ( SELECT L 
           FROM ( SELECT LEVEL AS L
                    FROM DUAL
                 CONNECT BY LEVEL < 1000)
          ORDER BY DBMS_RANDOM.VALUE)

此查询生成这样的输出(仅前3行):

| 001 | 138 |
| 002 | 281 |
| 003 | 177 |

有没有办法得到这样的东西(为每一行增加10行,将0-9添加为最后一个字符)(只扩展了两个源行以节省空间):

| 0010 | 1380 |
| 0011 | 1381 |
| 0012 | 1382 |
| 0013 | 1383 |
| 0014 | 1384 |
| 0015 | 1385 |
| 0016 | 1386 |
| 0017 | 1387 |
| 0018 | 1388 |
| 0019 | 1389 |
| 0020 | 2810 |
| 0021 | 2811 |
| 0022 | 2812 |
| 0023 | 2813 |
| 0024 | 2814 |
| 0025 | 2815 |
| 0026 | 2816 |
| 0027 | 2817 |
| 0028 | 2818 |
| 0029 | 2819 |

依此类推......(我可以编写程序,函数但我想要简单的select语句)

2 个答案:

答案 0 :(得分:3)

  

WBAR指出的错误。谢谢!

SELECT  r || L2, l || L2
FROM
(
        SELECT TO_CHAR(ROWNUM, '009') r, TO_CHAR(L, '009') l
        FROM
        (
                SELECT L
                FROM
                (
                    SELECT  LEVEL AS L
                    FROM    DUAL
                    CONNECT BY LEVEL < 1000
                )
                ORDER BY DBMS_RANDOM.VALUE
        )
)
CROSS JOIN
(
        SELECT  LEVEL -1 AS L2
        FROM    DUAL
        CONNECT BY LEVEL < 11
)
ORDER   BY
        1, 2;
/*
 0010    8460
 0011    8461
 0012    8462
 0013    8463
 0014    8464
 0015    8465
 0016    8466
 0017    8467
 0018    8468
 0019    8469
*/

答案 1 :(得分:1)

以下似乎可以做你想做的事:

SELECT TO_CHAR((R*10)+((ROWVAL/10-TRUNC(ROWVAL/10))*10), '0009') AS ROW_IDX,
       TO_CHAR(ROWVAL, '0009') AS ROW_VAL
  FROM (SELECT R, L*10     AS L10,
                  (L*10)+1 AS L11,
                  (L*10)+2 AS L12,
                  (L*10)+3 AS L13,
                  (L*10)+4 AS L14,
                  (L*10)+5 AS L15,
                  (L*10)+6 AS L16,
                  (L*10)+7 AS L17,
                  (L*10)+8 AS L18,
                  (L*10)+9 AS L19
          FROM (SELECT ROWNUM AS R, L
                  FROM (SELECT L 
                          FROM (SELECT LEVEL AS L
                                   FROM DUAL
                                   CONNECT BY LEVEL < 1000)
                          ORDER BY DBMS_RANDOM.VALUE)))
  UNPIVOT (ROWVAL FOR LVL IN (L10, L11, L12, L13, L14,
                              L15, L16, L17, L18, L19));

分享并享受。