简体   繁体   English

Oracle SQL ROWNUM和NEXTVAL

[英]Oracle SQL ROWNUM and NEXTVAL

I created a sequence 我创建了一个序列

CREATE SEQUENCE name_seq
START WITH 1
INCREMENT BY   1
NOCACHE
NOCYCLE;

Then used it in my query: 然后在我的查询中使用它:

select Name, ROWNUM, name_seq.NEXTVAL
from myTable;

Results into something like this: 结果变成这样:

+----+------+-------+
|Name|ROWNUM|NEXTVAL|
+----+------+-------+
|A   |     1|      1|     
|B   |     2|      2|
|C   |     3|      3| 
|D   |     4|      4|
|E   |     5|      5|
|F   |     6|      6|
|G   |     7|      7|
|H   |     8|      8|
|I   |     9|      9|
|J   |    10|     10|
+----+------+-------+

And from this, what I want the output to be is to use the next value of my sequence every after a number that I will declare. 从这开始,我希望输出是在要声明的数字之后使用序列的下一个值。 For example I'll use 4. The output should be like this: 例如,我将使用4。输出应如下所示:

In 1st run: 在第一轮中:

+----+------+-------+
|Name|ROWNUM|NEXTVAL|
+----+------+-------+
|A   |     1|      1|     
|B   |     2|      1|
|C   |     3|      1| 
|D   |     4|      1|
|E   |     5|      2|
|F   |     6|      2|
|G   |     7|      2|
|H   |     8|      2|
|I   |     9|      3|
|J   |    10|      3|
+----+------+-------+

Then in 2nd run: 然后在第二次运行中:

+----+------+-------+
|Name|ROWNUM|NEXTVAL|
+----+------+-------+
|A   |     1|      4|     
|B   |     2|      4|
|C   |     3|      4| 
|D   |     4|      4|
|E   |     5|      5|
|F   |     6|      5|
|G   |     7|      5|
|H   |     8|      5|
|I   |     9|      6|
|J   |    10|      6|
+----+------+-------+

try this, 尝试这个,

CREATE SEQUENCE name_test_seq
START WITH 1
INCREMENT BY   1
NOCACHE
NOCYCLE;

CREATE OR REPLACE FUNCTION get_next_val     (p_num NUMBER) RETURN NUMBER
IS
BEGIN
    IF p_num = 1 THEN
        RETURN name_test_seq.NEXTVAL;
    ELSE
        RETURN name_test_seq.CURRVAL;
    END IF;
END;
/

select rownum rown, get_next_val(MOD(rownum, :p_num))
  from dual
connect by rownum <= 10

Try this : 尝试这个 :

Select name,rownum,floor((name_seq.NEXTVAL-1)/4)+1 fl
from myTable

Just substract the sequence last number. 只需减去序列的最后一个数字。

with seq_cur_val as(
    select last_number seq_cv
    from user_sequences
    where sequence_name='NAME_SEQ'
)
select name, rownum,
    floor((name_seq.nextval-seq_cv)/4)+1
from myTable,seq_cur_val;

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

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