我想获取两列之间的数字列表。表值将用于生成更多行。
例如表1:
Key StartNum EndNum
--- -------- ------
A 1 3
B 6 8
我的输出应该是:
Key Num
--- ---
A 1
A 2
A 3
B 6
B 7
B 8
我试过这个,但它没有帮助我(我需要带键的行)。
我需要在 Oracle 11g 中解决这个问题。
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 填充它,因为上述方法包含表上的后续 decarts(因此需要不同的)。 http://www.dba-oracle.com/t_temporary_tables_sql.htm
这是贾斯汀解决方案的略微改编版本,发布于:获取两列之间的数字列表
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
,但我目前没有时间深入研究。
试试这个,
SELECT t.StartNum , t.StartNum , ROWNUM
FROM Table1 t , ALL_OBJECTS
WHERE ROWNUM between t.StartNum and t.StartNum
在事务 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