Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

can an analytic function be used to get the next greatest value?

wjpenfoldJun 12 2012 — edited Jun 12 2012
I have a table with values similar to this:

id term val
1 200720 aaa
1 200720 bbb
1 200720 ccc
1 201220 ddd
1 201220 eee

2 200720 qqq
2 200720 rrr
2 200920 sss

What I need, is to get the value of the next greater term (999999 if non exists) for each row within id, like this:

id term val next_term
1 200720 aaa 201220
1 200720 bbb 201220
1 200720 ccc 201220
1 201220 ddd 999999
1 201220 eee 999999

2 200720 qqq 200920
2 200720 rrr 200920
2 200920 sss 999999

I tried lead term over partitiion by id, but that just gives me the value in the next row. I looked at windowing, but my eyes crossed... Any ideas? I need the next higher value not the value in the next row. The next_term value should never be the same as the term value

CREATE TABLE WJPTEST
(
ID VARCHAR2(3 CHAR),
TERM VARCHAR2(6 CHAR),
VAL VARCHAR2(3 CHAR)
)
;

Insert into WJPTEST
(ID, TERM, VAL)
Values
('1', '200720', 'aaa');
Insert into WJPTEST
(ID, TERM, VAL)
Values
('1', '200720', 'bbb');
Insert into WJPTEST
(ID, TERM, VAL)
Values
('1', '200720', 'ccc');
Insert into WJPTEST
(ID, TERM, VAL)
Values
('1', '201220', 'ddd');
Insert into WJPTEST
(ID, TERM, VAL)
Values
('1', '201220', 'eee');
Insert into WJPTEST
(ID, TERM, VAL)
Values
('2', '200720', 'qqq');
Insert into WJPTEST
(ID, TERM, VAL)
Values
('2', '200720', 'rrr');
Insert into WJPTEST
(ID, TERM, VAL)
Values
('2', '200920', 'sss');
COMMIT;

Edited by: wjpenfold on Jun 12, 2012 10:08 AM
This post has been answered by Solomon Yakobson on Jun 12 2012
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 10 2012
Added on Jun 12 2012
7 comments
480 views