简体   繁体   English

使用键获取两列之间的数字列表

[英]Get list of numbers in between two columns with key

I want to get the list of numbers in between two columns. 我想获取两列之间的数字列表。 A tables values will be used to generate more rows. 表值将用于生成更多行。

eg Table1: 例如表1:

Key StartNum EndNum
--- -------- ------
A   1        3
B   6        8

My output should be: 我的输出应为:

Key Num
--- ---
A   1
A   2
A   3
B   6
B   7
B   8

I tried this , but it didn't help me (I need rows with the key). 我尝试了此方法 ,但对我没有帮助(我需要带有键的行)。

I need to solve this in Oracle 11g. 我需要在Oracle 11g中解决此问题。

a_horse_with_no_name-s solution would be 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

Output: 输出:

A   1                                     
A   2                                     
A   3                                     
B   6                                     
B   7                                     
B   8                                     

But I'd prefer creating a global temporary table and populate it from plsql, as the above method contains subsequent decarts on the table (thus the distinct required). 但是我更喜欢创建一个全局临时表并从plsql填充它,因为上述方法在表上包含后续的deart(因此需要不同的)。 http://www.dba-oracle.com/t_temporary_tables_sql.htm http://www.dba-oracle.com/t_temporary_tables_sql.htm

Create a store procedure in transact SQL 在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 

This is a slightly adapted version of Justin's solution posted in: 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

I'm not happy with the need for the distinct in the inner query, but I currently don't have the time to dig deeper into this. 我不是很满意,需要在distinct的内部查询,但我目前还没有更深入地研究这个的时候。

Try this, 尝试这个,

SELECT t.StartNum , t.StartNum , ROWNUM
FROM Table1 t , ALL_OBJECTS
WHERE ROWNUM between t.StartNum  and t.StartNum 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM