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!

Need help with RANK() on NULL data

515650May 5 2009 — edited May 6 2009
Hi All

I am using Oracle 10g and running a query with RANK(), but it is not returning a desired output. Pleas HELP!!

I have a STATUS table that shows the history of order status.. I have a requirement to display the order and the last status date (max). If there is any NULL date for an order then show NULL.

STATUS
------------
ORD_NO | STAT | DT
---------------------------------------------
1 | Open |
1 | Pending |
2 | Open |
2 | Pending |
3 | Open |1/1/2009
3 | Pending |1/6/2009
3 | Close |
4 | Open |3/2/2009
4 | Close |3/4/2009
Result should be (max date for each ORD_NO otherwise NULL):
ORD_NO |DT
---------------------------------------------
1 |
2 |
3 |
4 |3/4/2009
----------------------------------------------
CREATE TABLE Status (ORD_NO NUMBER, STAT VARCHAR2(10), DT DATE);
INSERT INTO Status VALUES(1, 'Open', NULL);
INSERT INTO Status VALUES(1, 'Pending', NULL);
INSERT INTO Status VALUES(2, 'Open', NULL);
INSERT INTO Status VALUES(2, 'Pending',NULL);
INSERT INTO Status VALUES(3, 'Open', '1 JAN 2009');
INSERT INTO Status VALUES(3,'Pending', '6 JAN 2009');
INSERT INTO Status VALUES(3, 'Close', NULL);
INSERT INTO Status VALUES(4, 'Open', '2 MAR 2009');
INSERT INTO Status VALUES(4, 'Close', '4 MAR 2009');
COMMIT;

I tried using RANK function to rank all the orders by date. So used ORDER BY cluse on date in descending order thinking that the null dates would be on top and will be grouped together by each ORD_NO.

SELECT ORD_NO, DT, RANK() OVER (PARTITION BY ORD_NO ORDER BY DT DESC)
FROM Status;

...but the result was something..
ORD_NO |DT |RANKING
---------------------------------------------
*1 | | 1*
*1 | | 1*
*2 | | 1*
*2 | | 1*3 | | 1
3 |1/6/2009 | 2
3 |1/1/2009 | 3
4 |3/4/2009 | 1
4 |3/2/2009 | 2
----------------------------------------------

I am not sure why didn't the first two ORD_NOs didn't group together and why ranking of 1 was assigned to them. I was assuming something like:
ORD_NO |DT |RANKING
---------------------------------------------
*1 | | 1*
*1 | | 2*
*2 | | 1*
*2 | | 1*
3 | | 1
3 |1/6/2009 | 2
3 |1/1/2009 | 3
4 |3/4/2009 | 1
4 |3/2/2009 | 2
----------------------------------------------

Please guide me if I am missing something here?

Regards
Sri
This post has been answered by 666352 on May 5 2009
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 3 2009
Added on May 5 2009
8 comments
2,369 views