2017-09-22 2 views
0

以下の例を参考にしてください。オラクル表で第1回目と第2回目との間のレコード数を取得する必要があります。

私は

Rownumber Values 
1 C21 
2 abc\ 
3 C25 
4 C23 
5 efg 
6 C21 
7 abc 
8 C25 
9 C21 
10 ABC 


I need the record count between the 1st and 2nd occurrence of C21. 
(i.e.,) 

Count b/n 1st and 2nd occurrence of 'C21' is = 4 

1 C21 
2 abc\ 
3 C25 
4 C23 
5 efg 
6 C21 

Count b/n 2nd and 3rd Occurence of 'C21' is = 2 

6 C21 
7 abc 
8 C25 
9 C21 

はあなたが同じに助けてもらえ、以下の値を「EMP」テーブルを持っています。

+2

MySQLやOracleの?両方の製品にタグを付けました。あなたはどちらを使っていますか? –

答えて

2

の関数を使用しrow_number()lag()

select val, rn, rn - lag(rn) over (order by rn) - 1 distance 
    from (select row_number() over (order by rnr) rn , rnr, val from emp) 
    where val = 'C21' 

テストデータ:

create table emp(rnr number(3), val varchar2(5)); 
insert into emp values (1, 'C21'); 
insert into emp values (2, 'abc\'); 
insert into emp values (3, 'C25'); 
insert into emp values (4, 'C23'); 
insert into emp values (5, 'efg'); 
insert into emp values (6, 'C21'); 
insert into emp values (7, 'abc'); 
insert into emp values (8, 'C25'); 
insert into emp values (9, 'C21'); 
insert into emp values (10, 'ABC'); 

結果:

VAL   RN DISTANCE 
----- ---------- ---------- 
C21   1 
C21   6   4 
C21   9   2 
+0

ありがとう:) – Vel

関連する問題