在from和to之间按顺序创建数字

时间:2014-05-13 10:54:18

标签: sql oracle

我有一个表,用下面的示例数据称之为sach_temp

TO_VALUE FROM_VALUE DATE_1

200      100        2/13/2014
238      234        2/13/2014

我希望生成如下所示的输出

VALUE   DATE_1
100     2/13/2014
101     2/13/2014
102     2/13/2014
103     2/13/2014
.
.
200     2/13/2014
234     2/13/2014
.
.
238     2/13/2014

我可以想到类似下面的内容,但它只适用于表格中的单行。有人可以指导我如何处理这个问题吗?

   SELECT from_value+rownum-1 value, date_1
     FROM 
    (SELECT     1 JUST_A_COL
          FROM DUAL
    CONNECT BY LEVEL <= (SELECT to_value-from_value+1 FROM sach_temp WHERE to_value=200)) a, sach_temp b
  WHERE to_value=200 

2 个答案:

答案 0 :(得分:2)

如果你的Oracle版本是11g或更高版本,你可以使用recursive with子句,查询只是:

with gen(max_num, min_num, value) as
(
  select max_num, min_num, value from mytable
  union all
  select max_num, min_num + 1, value from gen where min_num < max_num
)
select min_num as num, value 
from gen
order by min_num;

SQL小提琴:http://www.sqlfiddle.com/#!4/fc2c4/3

答案 1 :(得分:1)

假设两个值之间的最大差异为500.然后,您可以通过创建一个包含数字的表并使用join来完成此操作。这是一个例子:

with nums as (
      select level as lvl from dual
      connect by level < 500
     )
select (st.from_value + n.lvl - 1) as value, st.date_1
from sach_temp st join
     nums n
     on st.from_value + n.lvl - 1<= st.to_value;

编辑:

您无需猜测最大值。你可以计算:

with vmax as (
      select max(to_value - from_value + 1) as vmax
      from sach_temp
     ),
     nums as (
      select level as lvl from vmax
      connect by level < vmax.vmax
     )
select (st.from_value + n.lvl - 1) as value, st.date_1
from sach_temp st join
     nums n
     on st.from_value + n.lvl - 1<= st.to_value;