我正在编写一个在指定范围之间生成数字的查询。
我有一张桌子
NUM_RANGES
ID START_NUMBER END_NUMBER
-- ------------ ----------
1 1 5
2 6 10
我需要得到这个结果:
ID NUMBER
-- ------
1 1
1 2
1 3
1 4
1 5
2 6
2 7
2 8
2 9
2 10
使用此查询,我可以获得正确的结果,但仅适用于where子句中的指定id:
select id, start_number + level - 1 next_tag
from (select id, start_number,end_number
from NUM_RANGES
where id = 1
)
connect by level <= end_number - start_number + 1
没有“where id = 1”我得到62行重复,其中有明显的帮助,但更大的范围1 - 200,200-500它的工作太慢..
感谢您的帮助!
答案 0 :(得分:0)
在Oracle 12c上,您可以使用CROSS APPLY:
select *
from num_ranges
cross apply(
select level - 1 + start_number as my_new_number
from dual
connect by level <= end_number - start_number + 1
);
答案 1 :(得分:0)
在Oracle 11.2及更早版本中,您可以使用分层查询:
with
num_ranges ( id, start_number, end_number ) as (
select 1, 1, 5 from dual union all
select 2, 9, 12 from dual
)
-- End of simulated input data (for testing purposes only, not part of the solution).
-- SQL query begins below this line.
select id, start_number + level - 1 as nmbr
from num_ranges
connect by level <= end_number - start_number + 1
and prior id = id
and prior sys_guid() is not null
order by id, nmbr -- If needed
;
ID NMBR
---------- ----------
1 1
1 2
1 3
1 4
1 5
2 9
2 10
2 11
2 12
具体而言,如果不将新行与同一id
的新行链接,则会产生疯狂数量的不必要的行。这就是您需要prior id = id
的原因。需要附加条件prior sys_guid() is not null
,以便Oracle不会看到它不应该看到它们的周期(这些周期是由&#34; prior id = id
&#34;)引起的。< / p>
在Oracle 12.1或更高版本中,您可以使用lateral
子句:
select n.id, l.nmbr
from num_ranges n,
lateral ( select start_number + level - 1 as nmbr from dual
connect by level <= end_number - start_number + 1 ) l
order by id, nmbr -- If needed
;
答案 2 :(得分:0)
这应该有效。也很快。
with cte as (select 0 as c from dual)
, cte4 as (select c from cte union all select c from cte union all select c from cte union all select c from cte)
, cte256 as (select t0.c from cte4 t0, cte4 t1, cte4 t2, cte4 t3)
, nums as (select row_number() over(order by null) as n from cte256 t0, cte256 t1, cte256 t2)
select NR.id, nums.n as NUMBER_
from nums
join NUM_RANGES NR on nums.n between NR.START_NUMBER and NR.END_NUMBER
;