我想获取两列之间的数字列表。表值将用于生成更多行。
e.g 表1:
Key StartNum EndNum
--- -------- ------
A 1 3
B 6 8
我的输出应该是:
Key Num
--- ---
A 1
A 2
A 3
B 6
B 7
B 8
我尝试了this,但它没有帮助我(我需要带钥匙的行)。
我需要在Oracle 11g中解决这个问题。
答案 0 :(得分:1)
a_horse_with_no_name-s解决方案将是
SELECT distinct Key,(level + StartNum)-1 Num
FROM Table1
CONNECT BY (LEVEL +StartNum ) <= EndNum+1
order by Key, Num
输出:
A 1
A 2
A 3
B 6
B 7
B 8
但是我更喜欢创建一个全局临时表并从plsql填充它,因为上面的方法包含了表上的后续decart(因此需要不同)。 http://www.dba-oracle.com/t_temporary_tables_sql.htm
答案 1 :(得分:0)
在transact SQL中创建存储过程
Create Procedure GetRangeFromTable
As
Begin
create table #Result(
code varchar(50),
num int
)
Declare
@code varchar(50),
@start int ,
@end int
DECLARE num_cursor CURSOR FOR Select * from Table1
OPEN num_cursor
FETCH NEXT FROM num_cursor
INTO @code, @start, @end
WHILE @@FETCH_STATUS = 0
BEGIN
While @start <= @end
Begin
Insert into #Result(code,num) Values (@code,@start)
Set @start= @start + 1
End
FETCH NEXT FROM num_cursor
INTO @code, @start, @end
END
Select * from #Result
CLOSE num_cursor
DEALLOCATE num_cursor
End
答案 2 :(得分:0)
这是Justin的解决方案的略微改编版本:get list of numbers in between two columns
select key, num
from (
select distinct t1.key, t1.startnum + level - 1 num, t1.startnum, t1.endnum
from table1 t1
connect by level <= (select t2.endnum from table1 t2 where t1.key = t2.key)
) t
where num between t.startnum and t.endnum
order by key, num
我对内部查询中distinct
的需求感到不满意,但我目前没有时间深入研究这个问题。
答案 3 :(得分:0)
试试这个,
SELECT t.StartNum , t.StartNum , ROWNUM
FROM Table1 t , ALL_OBJECTS
WHERE ROWNUM between t.StartNum and t.StartNum