获取两列之间的数字列表

时间:2010-10-19 19:31:39

标签: sql sql-server oracle

我在oracle中有一个table1(startnumber,endnumber);

现在我需要从table1

中选择startnumber和endnumber之间的所有数字

数据,例如

    table1
   startnumber      endnumber
     10                15
    18                 22
    34                 50

Now I need the result set as:

10,11,12,13,14,15,18,19,20,21,22,34,35..... and so on

我该怎么做

2 个答案:

答案 0 :(得分:3)

如果您希望以逗号分隔值,则可以这样做(或者如果在11gr2上使用listAgg

WITH NUMS AS(
     SELECT 10 STARTNR  , 15 ENDNR  FROM DUAL UNION
    SELECT 18 STARTNR  , 22 ENDNR  FROM DUAL UNION
    SELECT 34 STARTNR  , 50 ENDNR  FROM DUAL )       , 
 NUMSBETWEEN AS(
     SELECT distinct (level + startnr)-1 seq , startnr, endnr
       FROM NUMS
      CONNECT BY (LEVEL +STARTNR ) <= ENDNR+1
      )
SELECT startnr,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(seq,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS seq
FROM   (SELECT startnr,
               seq,
               ROW_NUMBER() OVER (PARTITION BY startnr ORDER BY seq) AS curr,
               ROW_NUMBER() OVER (PARTITION BY startnr ORDER BY seq) -1 AS prev
        FROM   numsBetween)
GROUP BY startnr
CONNECT BY prev = PRIOR curr AND startnr = PRIOR startnr
START WITH CURR = 1;

STARTNR SEQ


10 10,11,12,13,14,15
18 18,19,20,21,22
34 34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50

答案 1 :(得分:2)

SQL> ed
Wrote file afiedt.buf

  1  with t as (
  2    select 10 startnum, 15 endnum from dual
  3    union all
  4    select 18, 22 from dual
  5    union all
  6    select 34, 50 from dual
  7  )
  8  select lvl
  9    from (select level lvl
 10            from dual
 11         connect by level <= (select max(endnum) from t)) a
 12   where exists (select 1
 13                   from t
 14*                 where lvl between t.startnum and t.endnum)
SQL> /

       LVL
----------
        10
        11
        12
        13
        14
        15
        18
        19
        20
        21
        22
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50

28 rows selected.

如果最低起始数与最大结束数相比相对较大,则可以更改CONNECT BY子查询以生成从MIN(起始编号)到MAX(结束编号)的数字,而不是从1到MAX(结束编号),这应该是更有效率。